LeetCode 3139: Minimum Cost to Equalize Array Solution
Master LeetCode problem 3139 (Minimum Cost to Equalize Array), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3139. Minimum Cost to Equalize Array
Problem Explanation
Explanation:
To solve this problem, we need to find the minimum cost required to make all elements in the array equal. We can achieve this by considering two scenarios for each element in the array:
- Increasing the value at a single index by
cost1. - Increasing the values at two different indices by
cost2.
We will iterate through the array and calculate the cost for each of the two scenarios. At each step, we will choose the minimum cost among the two scenarios. Finally, we return the total minimum cost modulo 10^9 + 7.
:
Solution Code
class Solution {
public int minCost(int[] nums, int cost1, int cost2) {
long totalCost = 0;
for (int i = 0; i < nums.length - 1; i++) {
totalCost += Math.min(cost1 * (long)(nums[i + 1] - nums[i]), cost2);
}
return (int)(totalCost % 1000000007);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3139 (Minimum Cost to Equalize Array)?
This page provides optimized solutions for LeetCode problem 3139 (Minimum Cost to Equalize Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3139 (Minimum Cost to Equalize Array)?
The time complexity for LeetCode 3139 (Minimum Cost to Equalize Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3139 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3139 in Java, C++, or Python.