- 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 water pouring game has all winner or not
Suppose we have an array A with n elements and have another number s. There is one empty water mug and n non-empty water mugs on the table. In a game, there are few players. In each move, a player takes a non-empty mug of water and pours all water from it into the cup. If it overfills, the player will lost. We have to check whether all of them will be winner or not (the cup will not overfill). If one up is already filled completely, the next player will not play his/her move. Here s is the capacity of the empty cup and A[i] is amount of water present in ith cup.
So, if the input is like A = [3, 1, 3]; s = 4, then the output will be True, because by first and second player, the cup will be filled. For the last one, the player will not play that move.
Steps
To solve this, we will follow these steps −
k := 0 n := size of A sort the array A for initialize i := 0, when i < n - 1, update (increase i by 1), do: k := k + A[i] if k > s, then: return false Otherwise return true
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; bool solve(vector<int> A, int s){ int k = 0; int n = A.size(); sort(A.begin(), A.end()); for (int i = 0; i < n - 1; i++) k += A[i]; if (k > s) return false; else return true; } int main(){ vector<int> A = { 3, 1, 3 }; int s = 4; cout << solve(A, s) << endl; }
Input
{ 3, 1, 3 }, 4
Output
1