Minimum number of items to be delivered using C++.

C++Server Side ProgrammingProgramming

Problem statement

Given an array of size, N represents buckets, each array index containing items. Given K tours within which all of the items are needed to be delivered. It is allowed to take items from only one bucket in 1 tour. The task is to tell the minimum number of items needed to be delivered per tour so that all of the items can be delivered within K tours.

If there are 5 buckets with item = {1, 3, 5, 7, 9} and 10 tours then we can deliver 3 items per tour By delivering 3 items at a time,

  • 1st bucket size is 1 hence the number of required tours = 1

  • 2nd bucket size is 3 hence the number of required tours = 1

  • 3rd bucket size is 5 hence the number of required tours = 2 (3 + 2 items per tour)

  • 4th bucket size is 7 hence the number of required tours = 3 (3 + 3 + 1 items per tour)

  • 5th bucket size is 9 hence the number of required tours = 3 (3 + 3 + 3 items per tour)

Total number of tours = 10

Algorithm

1. find the minimum number of items to be distributed per delivery
2. iterate from 1 to the maximum value of items in a bucket and calculate the number of tours required for each bucket and find the total number of tours for complete delivery
3. The first such value with tours less than or equals K gives the required number

Example

#include <iostream>
#include <climits>
#include <cmath>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int minItemsDeliveried(int *arr, int n, int k){
   int maxElement = INT_MIN;
   for (int i = 0; i < n; ++i) {
      maxElement = max(maxElement, arr[i]);
   }
   for (int i = 1; i < maxElement + 1; ++i) {
      int tours = 0;
      for (int j = 0; j < n; ++j) {
         if (arr[i] % i == 0) {
            tours += arr[j] / i;
         } else {
            tours += floor(arr[j] / i) + 1;
         }
      }
      if (tours <= k) {
         return i;
      }
   }
   return 1;
}
int main(){
   int arr[] = {1, 3, 5, 7, 9};
   int k = 10;
   cout << "Minimum items to be delivered = " <<
   minItemsDeliveried(arr, SIZE(arr), k) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Minimum items to be delivered = 3
raja
Published on 31-Oct-2019 07:00:39
Advertisements