Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find minimum operations to make array equal using Python
Suppose we have a value n, consider an array nums with n elements, where arr[i] = (2*i)+1 for all i. Now in one operation, we can choose two indices x and y where 0 <= x, y < n and subtract 1 from nums[x] and add 1 to nums[y]. We have to make all the elements of the array same. So if we have n we have to find the minimum number of operations required to make all the elements of nums same.
Understanding the Problem
For n = 4, the array is [1, 3, 5, 7]. To make all elements equal, we need to find the target value and calculate minimum operations.
The target value for making all elements equal is the average of all elements, which is sum(arr) / n = (1+3+5+7) / 4 = 4.
Solution Approach
To solve this, we will follow these steps ?
Initialize
ans = 0If n is 1, return 0 (already equal)
Calculate
q = (n//2) - 1Initialize
j = 1While
q >= 0, add(n-j)to ans, decrement q, and increment j by 2Return ans
Example
def solve(n):
ans = 0
if n == 1:
return ans
q = (n // 2) - 1
j = 1
while q >= 0:
ans = ans + (n - j)
q -= 1
j += 2
return ans
n = 4
result = solve(n)
print(f"Minimum operations for n = {n}: {result}")
# Let's also show the array transformation
arr = [2*i + 1 for i in range(n)]
print(f"Original array: {arr}")
print(f"Target value: {sum(arr) // n}")
Minimum operations for n = 4: 4 Original array: [1, 3, 5, 7] Target value: 4
How It Works
For n = 4, the transformation steps are:
[1, 3, 5, 7]?[2, 3, 5, 6](1 operation)[2, 3, 5, 6]?[3, 3, 5, 5](1 operation)[3, 3, 5, 5]?[4, 3, 4, 5](1 operation)[4, 3, 4, 5]?[4, 4, 4, 4](1 operation)
Testing with Different Values
def solve(n):
ans = 0
if n == 1:
return ans
q = (n // 2) - 1
j = 1
while q >= 0:
ans = ans + (n - j)
q -= 1
j += 2
return ans
# Test with different values
test_cases = [1, 2, 3, 4, 5, 6]
for n in test_cases:
result = solve(n)
arr = [2*i + 1 for i in range(n)]
print(f"n = {n}, array = {arr}, operations = {result}")
n = 1, array = [1], operations = 0 n = 2, array = [1, 3], operations = 1 n = 3, array = [1, 3, 5], operations = 2 n = 4, array = [1, 3, 5, 7], operations = 4 n = 5, array = [1, 3, 5, 7, 9], operations = 6 n = 6, array = [1, 3, 5, 7, 9, 11], operations = 9
Conclusion
The algorithm efficiently calculates minimum operations by using the pattern that elements need to be redistributed to achieve the average value. The time complexity is O(n) and space complexity is O(1).
