C++ code to check pile count is valid from second day


Suppose we have two arrays X and Y of same size. There are stone piles with X[i] number of stones on ith index on the first day and on the second day ith index has Y[i] number of stones. On the first day many members have come. Either they do nothing or they add few stones to some pile or they swap few stones from one pile to another. We have to check whether Y is valid from X or not.

So, if the input is like X = [1, 2, 3, 4, 5]; Y = [2, 1, 4, 3, 5], then the output will be True, because move one stone from second pile to first pile, one stone from 4th pile to 3rd pile.

Steps

To solve this, we will follow these steps −

n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   s := s + A[i]
for initialize i := 0, when i < n, update (increase i by 1), do:
   d := d + B[i]
return (if d > s, then false, otherwise true)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool solve(vector<int> A, vector<int> B){
   int n = A.size(), d = 0, s = 0;
   for (int i = 0; i < n; i++)
      s += A[i];
   for (int i = 0; i < n; i++)
      d += B[i];
   return d > s ? false : true;
}
int main(){
   vector<int> X = { 1, 2, 3, 4, 5 };
   vector<int> Y = { 2, 1, 4, 3, 5 };
   cout << solve(X, Y) << endl;
}

Input

{ 1, 2, 3, 4, 5 }, { 2, 1, 4, 3, 5 }

Output

1

Updated on: 29-Mar-2022

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements