Make Array elements equal by increasing or decreasing the elements by 1
Last Updated :
25 Aug, 2023
Given an integer N. Consider an array arr having N elements where arr[i] = 2*i + 1. (The array is 0-indexed). Your task is to find the minimum number of such operations required to make all the elements of the array equal where you are allowed to select two indices i and j and increase arr[i] by 1 and decrease arr[j] by 1.
Example:
Input: N = 3
Output: 2
Explanation: Initially, the array is {1, 3, 5}. If we perform the operation once on the indices 0 and 2, the resulting array will be {2, 3, 4}. If we again perform the operation once on the indices 0 and 2, the resulting array will be {3, 3, 3}. Hence, the minimum operations required is 2
in this case.
Input: N = 2
Output: 1
Explanation: The array initially is {1, 3}. After performing an operation the array will be {2, 2}. Hence, the answer is 1 in this case.
Approach: This can be solved with the following idea:
The idea is to find a pattern to calculate the answer. Since the formula which needs to be followed is arr[i] = 2*i+1 (The array is 0-indexed). So the array of size 4 will look like = {1, 3, 5, 7}, to make all elements equal in min operations, we need to find the mean of the smallest and largest elements.
Below are the steps involved in the implementation of the code:
- Set answer = N / 2.
- Multiply (N+1)/2 with the answer
- Return answer
Below is the implementation for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long int minOperations( int N)
{
long long int ans = N / 2;
ans *= (N + 1) / 2;
return ans;
}
int main()
{
int n = 5;
long long ans = minOperations(n);
cout << ans;
return 0;
}
|
Java
public class Main {
public static long minOperations( int N) {
long ans = N / 2 ;
ans *= (N + 1 ) / 2 ;
return ans;
}
public static void main(String[] args) {
int n = 5 ;
long ans = minOperations(n);
System.out.println(ans);
}
}
|
Python3
def minOperations(N):
ans = N / / 2
ans * = (N + 1 ) / / 2
return ans
n = 5
ans = minOperations(n)
print (ans)
|
C#
using System;
public class GFG
{
public static long MinOperations( int N)
{
long ans = N / 2;
ans *= (N + 1) / 2;
return ans;
}
public static void Main( string [] args)
{
int n = 5;
long ans = MinOperations(n);
Console.WriteLine(ans);
}
}
|
Javascript
function minOperations(N) {
let ans = Math.floor(N / 2) * Math.floor((N + 1) / 2);
return ans;
}
const n = 5;
const ans = minOperations(n);
console.log(ans);
|
Time Complexity: O(1) As we are calculating the answer without using any loop, so the time complexity is O(1)
Auxiliary Space: O(1) As we are not using any extra space so the space complexity is O(1)
Share your thoughts in the comments
Please Login to comment...