- 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 count maximum hay-bales on first pile
Suppose we have an array A with n elements and another value d. A farmer has arranged n haybale piles on the firm. The ith pile contains A[i] hay-bales. Every day a cow can choose to move one hay-bale in any pile to an adjacent pile. The cow can do this on a day otherwise do nothing. The cow wants to maximize the hay-bales in first pile in d days. We have to count the maximum number of hay-bales on the first pile.
So, if the input is like d = 5; A = [1, 0, 3, 2], then the output will be 3, because on the first day move from 3rd to 2nd, on second day again move from 3rd to second, then on next two days, pass 2nd to first.
Steps
To solve this, we will follow these steps −
a0 := A[0] n := size of A for initialize i := 1, when i < n, update (increase i by 1), do: ai := A[i] w := minimum of ai and d / i a0 := a0 + w d := d - w * i return a0
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(int d, vector<int> A){ int a0 = A[0]; int n = A.size(); for (int i = 1; i < n; i++){ int ai = A[i]; int w = min(ai, d / i); a0 += w; d -= w * i; } return a0; } int main(){ int d = 5; vector<int> A = { 1, 0, 3, 2 }; cout << solve(d, A) << endl; }
Input
5, { 1, 0, 3, 2 }
Output
3
Advertisements