C++ Program to find minimum possible ugliness we can achieve of towers


Suppose we have an array A with n elements. Consider there are n block towers in a row. The ith tower has height A[i]. In a single day, we can perform the operation: Select two indices i and j (i != j) and move back from tower i to j. It will decrease A[i] by 1 and increase A[j] by 1. The ugliness of the buildings is max(A) − min(A). We have to find the minimum possible ugliness we can achieve.

So, if the input is like A = [1, 2, 3, 1, 5], then the output will be 1, because we can do three operations for i=2 and j=0, the new array will now be [2,2,2,1,5], then for i = 4 and j = 3, array will be [2,2,2,2,4], and for i = 4 and j = 2, the array is [2,2,3,2,3].

Steps

To solve this, we will follow these steps −

sum := 0
x := 0
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   sum := sum + A[i]
if sum mod n is same as 0, then:
   return 0
return 1

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> A) {
   int sum = 0, x = 0;
   int n = A.size();
   for (int i = 0; i < n; i++)
      sum += A[i];
   if (sum % n == 0)
      return 0;
   return 1;
}
int main() {
   vector<int> A = { 1, 2, 3, 1, 5 };
   cout << solve(A) << endl;
}

Input

{ 1, 2, 3, 1, 5 }

Output

1

Updated on: 04-Mar-2022

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements