How Chocolate dived and distribute in C++ ?

  C & C ++ Interview Q&A

Dear readers, in this tutorial today, learn how Chocolate dived and delivered in C ++?

A chocolate bar containing some portion. Each chunks has its own sweetness given by a list called sweetness. If we want to share chocolate among K friends, we start cutting the chocolate bar into K + 1 pieces using K cuts, now each piece has a few consecutive pieces. If we remove the piece with minimal total sweetness and give the other pieces to our friends. We need to find out the maximum sweetness of the slice we can get by cutting the chocolate bar better.

So, if the input is like sweetness = [1,2,3,4,5,6,7,8,9], K = 5, then the output will be 6 because you can divide the chocolate into 1,2. , 3], [4,5], [6], [7], [8], [9] These pieces.

#include <bits/stdc++.h>
using namespace std;
class program{
   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(){
   program ob;
   vector<int> v = {1,2,3,4,5,6,7,8,9};
   cout << (ob.maximizeSweetness(v, 5));
}

Result

6

LEAVE A COMMENT