Find the number of boxes to be removed in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] in which each element represents a pile of boxes (each of unit height). Our task is to find the number of boxes to be removed.

The person is standing at index 0 of the array at the height of the pile of boxes and he needs to move to the end of the array. The condition to move from one pile to the next is by jumping to the next.

Jump is possible only when the next pile is at the same height or is at height less than it. If the height of the next pile is greater the person needs to remove boxes from the next pile, till the height becomes equal. We need to find the total number of boxes that will be removed while going from the first box to the last one.

Let’s take an example to understand the problem,

Input : arr[] = {5, 7, 3 , 1, 2}
Output : 3

Explanation

Initially, the person is a height 5.

Step 1 − To go to the second position which has 7 height, the person needs to remove 2 boxes.

Step 2 − To go to the third position at height 3, no boxes are removed.

Step 3 − To go to the next position at height 1, no boxes are removed.

Step 4 − To go to the next position at height 2, one box is removed. This makes the number of boxes removed equals 3.

Solution Approach

A simple solution to the problem is by traversing the array from start to end and checking if the next element is greater than the current one. If yes, then add their difference to the boxesRemoved variable which holds the total number of boxes that will be removed. At last, we will return boxesRemoved.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findBoxesRemoved(int arr[], int n){
   int boxesRemoved = 0;
   for (int i = 0; i < n-1; i++) {
      if (arr[i] < arr[i+1])
         boxesRemoved += (arr[i+1] - arr[i]);
   }
   return boxesRemoved;
}
int main(){
   int arr[] = { 5, 7, 3 , 1, 2, 6 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The total number of boxes to be removed to reach the end is "<<findBoxesRemoved(arr, n);
   return 0;
}

Output

The total number of boxes to be removed to reach the end is 7
raja
Updated on 24-Jan-2022 12:26:25

Advertisements