C++ program to check we can rearrange array in such a way that given formula returns m or not

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements and another number m. We have to check whether we can rearrange the array in such a way that

$$\mathrm{\sum_{i=1}^{n} \sum_{j=1}^{n}\frac{A[j]}{j} = m}$$

There will be no rounding in A[j]/j operation.

So, if the input is like A = [2, 5, 1]; m = 8, then the output will be True, because for the arrangement of [1, 2, 5], (1/1 + 2/2 + 5/3) + (2/2 + 5/3) + (5/3) = 8

steps

To solve this, we will follow these steps −

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

Example

Let us see the following implementation to get better understanding −

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

bool solve(vector<int> A, int m) {
   long sum = 0;
   int n = A.size();
   for (int i = 0; i < n; ++i) {
      sum += A[i];
   }
   if (sum == m)
      return true;
   else
      return false;
}

int main() {
   vector<int> A = { 2, 5, 1 };
   int m = 8;
   cout << solve(A, m) << endl;
}

Input

{ 2, 5, 1 }, 8

Output

1
raja
Updated on 03-Mar-2022 05:43:20

Advertisements