C++ Program to get difference between maximum and minimum water in barrels

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements and another value k. We have n barrels lined up in a row, they are numbered from left to right from one. Initially, the i-th barrel contains A[i] liters of water. We can pour water from one barrel to another. In one move, we can take two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y. (assume that barrels have infinite capacity). We have to find the maximum possible difference between the maximum and the minimum amount of water in the barrels, if we can pour water at most k times.

Problem Category

An array in the data structure is a finite collection of elements of a specific type. Arrays are used to store elements of the same type in consecutive memory locations. An array is assigned a particular name and it is referenced through that name in various programming languages. To access the elements of an array, indexing is required. We use the terminology 'name[i]' to access a particular element residing in position 'i' in the array 'name'. Various data structures such as stacks, queues, heaps, priority queues can be implemented using arrays. Operations on arrays include insertion, deletion, updating, traversal, searching, and sorting operations. Visit the link below for further reading.

https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm

So, if the input of our problem is like A = [5, 5, 5, 5]; k = 1, then the output will be 10.

Steps

To solve this, we will follow these steps −

n := size of A
sum := 0
sort the array A
sum := A[n - 1]
for initialize i := 0, when i < k, update (increase i by 1), do:
   sum := sum + A[n - 2 - i]
return sum

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A, int k){
   int n = A.size();
   int sum = 0;
   sort(A.begin(), A.end());
   sum = A[n - 1];
   for (int i = 0; i < k; i++){
      sum = sum + A[n - 2 - i];
   }
   return sum;
}
int main(){
   vector<int> A = { 5, 5, 5, 5 };
   int k = 1;
   cout << solve(A, k) << endl;
}

Input

{ 5, 5, 5, 5 }, 1

Output

10
raja
Updated on 08-Apr-2022 11:04:27

Advertisements