Divide Chocolate in C++


Suppose we have one chocolate bar that consists of some chunks. In each chunk it has its own sweetness given by a list called sweetness. If we want to share the chocolate among K friends so we start cutting the chocolate bar into K+1 piece using K cuts, now each piece consists of some consecutive chunks. If we take out the piece with the minimum total sweetness and give the other pieces to our friends. We have to find the maximum total sweetness of the piece we can get by cutting the chocolate bar optimally.

So, if the input is like sweetness = [1,2,3,4,5,6,7,8,9], K = 5, then the output will be 6 as You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9] these pieces.

To solve this, we will follow these steps −

  • Define a function ok(), this will take an array v, cuts, maxVal,

  • counter := 0, temp := 0

  • for initialize i := 0, when i <= size of v, update (increase i by 1), do −

    • if temp >= maxVal, then

      • (increase counter by 1)

      • temp := 0

    • if i is same as size of v, then −

      • Come out from the loop

    • temp := temp + v[i]

  • return true when counter >= cuts

  • From the main method do the following:

  • maxa := -1

  • n := size of s

  • low := 0, high := 0

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • low := minimum of low and s[i]

    • high := high + s[i]

  • (increase high by 1)

  • while low < high, do −

    • mid := low + (high - low + 1) / 2

    • if ok(s, k + 1, mid) is true, then −

      • low := mid

    • Otherwise

      • high := mid - 1

  • return low

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool ok(vector <int> v, int cuts, int maxVal){
      int counter = 0;
      int temp = 0;
      for (int i = 0; i <= v.size(); i++) {
         if (temp >= maxVal) {
            counter++;
            temp = 0;
         }
         if (i == v.size()) {
            break;
         }
         temp += v[i];
      }
      return counter >= cuts;
   }
   int maximizeSweetness(vector<int>& s, int k) {
      int maxa = -1;
      int n = s.size();
      int low = 0;
      int high = 0;
      for (int i = 0; i < n; i++) {
         low = min(low, s[i]);
         high += s[i];
      }
      high++;
      while (low < high) {
         int mid = low + (high - low + 1) / 2;
         if (ok(s, k + 1, mid))
            low = mid;
         else
            high = mid - 1;
      }
      return low;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,4,5,6,7,8,9};
   cout << (ob.maximizeSweetness(v, 5));
}

Input

{1,2,3,4,5,6,7,8,9}, 5

Output

6

Updated on: 11-Jul-2020

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements