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.


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


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;


5, { 1, 0, 3, 2 }



Updated on: 15-Mar-2022


Kickstart Your Career

Get certified by completing the course

Get Started