Construct Target Array With Multiple Sums in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers target. From a starting array A consisting of all 1's, we can perform the following procedure −

  • Consider x be the sum of all elements currently in our array.

  • Choose index i, in range 0 to n, where n is the size of the array and set the value of A at index i to x.

  • We can repeat this procedure as many times as we need.

We have to check whether it is possible to make the target array from A otherwise return False.

So, if the input is like [3,9,5], then the output will be True, as we can start with index [1,1,1], then sum is 3 at index 0, then the array is [3,1,1], then the sum is 5, at index 2, then the array is [3,1,5], then the sum is 9, at index 1, so array is [3,9,5].

To solve this, we will follow these steps −

  • sum := 0

  • n := size of target

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • sum := sum + target[i]

  • Define priority queue pq, and initialize it with target array

  • while top element of pq > sum, do −

    • x := top element of pq

    • delete element from pq

    • insert 2 * x - sum into pq

    • sum := x

  • return true when sum is same as size of target, otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   bool isPossible(vector<int>& target) {
      lli sum = 0;
      int n = target.size();
      for (int i = 0; i < n; i++) {
         sum += target[i];
      }
      priority_queue<int> pq(target.begin(), target.end());
      while (pq.top() * 2 > sum) {
         int x = pq.top();
         pq.pop();
         pq.push(2 * x - sum);
         sum = x;
      }
      return sum == (int)target.size();
   }
};
main(){
   Solution ob;
   vector<int> v = {3,9,5};
   cout << (ob.isPossible(v));
}

Input

{3,9,5}

Output

1
raja
Published on 08-Jun-2020 11:37:30
Advertisements