LeetCode 1551: Minimum Operations to Make Array Equal Solution
Master LeetCode problem 1551 (Minimum Operations to Make Array Equal), a medium 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.
1551. Minimum Operations to Make Array Equal
Problem Explanation
Explanation
To make all elements of the array equal, we need to perform operations that decrease some elements and increase others. Since we can only subtract 1 from one element and add 1 to another in one operation, the difference between the two elements should be divisible by 2. The target value for all elements will be the middle value in the sorted array. We can calculate the number of operations needed by iterating through the array and calculating the absolute difference between the target value and each element.
-
Algorithmic Idea:
- Calculate the target value by finding the middle element in the sorted array.
- Iterate through the array and calculate the total operations needed by summing the absolute differences between the target value and each element.
- Return the total operations.
-
Time Complexity: O(n)
-
Space Complexity: O(1)
Solution Code
class Solution {
public int minOperations(int n) {
int target = (n % 2 == 0) ? (n / 2) * (n / 2) : ((n / 2) * (n / 2 + 1));
int operations = 0;
for (int i = 0; i < n / 2; i++) {
operations += Math.abs((2 * i + 1) - target);
}
return operations;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1551 (Minimum Operations to Make Array Equal)?
This page provides optimized solutions for LeetCode problem 1551 (Minimum Operations to Make Array Equal) 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 1551 (Minimum Operations to Make Array Equal)?
The time complexity for LeetCode 1551 (Minimum Operations to Make Array Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1551 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1551 in Java, C++, or Python.