Minimize the total number of teddies to be distributed in C++

C++Server Side ProgrammingProgramming

Problem statement

Given N number of students and an array which represent the mark obtained by students. School has dicided to give them teddy as a price. Hoever, school wants to save money, so they to minimize the total number of teddies to be distrubuted by imposing following constrain −

  • All students must get atleast one teddy
  • If two students are sitting next to each other then student with the higher marks must get more
  • If two students have same marks then they are allowed to get different number of teddies

Example

Let us suppose there are 3 students and marks obtained are represented in array as −

arr[] = {2, 3, 3}
So, total number of teddies to be distributed:
{1, 2, 1} i.e. 4 teddies

Algorithm

This problem can be solved using dynamic programming as follows −

1. Create a table of size N and initialize it with 1 as each student must get atleast one teddy
2. Iterate over marks array and perform below step:
   a. If current student has more marks than previous student then:
      i. Get the number of teddies given to the previous student
      ii. Increment teddie count by 1
   b. If current student has lesser marks than previous student then:
      i. Review and change all the values assigned earlier

Example

#include <iostream>
#include <algorithm>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int teddieDistribution(int *marks, int n) {
   int table[n];
   fill(table, table + n, 1);
   for (int i = 0; i < n - 1; ++i) {
      if (marks[i + 1] > marks[i]) {
         table[i + 1] = table[i] + 1;
      } else if (marks[i] > marks[i + 1]) {
         int temp = i;
         while (true) {
            if (temp >= 0 && (marks[temp] >
            marks[temp + 1])) {
               if (table[temp] >
               table[temp + 1]) {
                  --temp;
                  continue;
               } else {
                  table[temp] =
                  table[temp + 1] + 1;
                  --temp;
               }
            } else {
               break;
            }
         }
      }
   }
   int totalTeddies = 0;
   for (int i = 0; i < n; ++i) {
      totalTeddies += table[i];
   }
   return totalTeddies;
}
int main() {
   int marks[] = {2, 6, 5, 2, 3, 7};
   int totalTeddies = teddieDistribution(marks,
   SIZE(marks));
      cout << "Total teddies to be distributed: " <<
   totalTeddies << "\n";
      return 0;
}

Output

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

Total teddies to be distributed: 12
raja
Published on 22-Oct-2019 12:20:29
Advertisements