- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements