Reducing Dishes in C++


Suppose there is a chef. And he has collected data on the satisfaction level of his n dishes. The Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is actually the time taken

to cook that dish including previous dishes multiplied by its satisfaction level So time[i]*satisfaction[i].

We have to find the maximum sum of Like-time coefficient that the chef can obtain after dishes preparation. Dishes can be ready in any order and the chef can discard some dishes to get this maximum value.

So, if the input is like [-1,-7,0,6,-7], then the output will be 17, After removing second and last dish, the maximum total like-time coefficient will be -1*1 + 0*2 + 6*3 = 17.

To solve this, we will follow these steps −

  • Define an array dp of size: 505 x 505.

  • Define a function solve(), this will take idx, time, an array v,

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

    • return 0

  • if dp[idx, time] is not equal to -1, then −

    • return dp[idx, time]

  • ret := -inf

  • ret := maximum of solve(idx + 1, time, v) and v[idx] * time + solve(idx + 1, time + 1, v)

  • dp[idx, time] := ret

  • return ret

  • From the main method do the following −

  • Fill this -1 with dp

  • sort the array v

  • return solve(0, 1, v)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int dp[505][505];
   int solve(int idx, int time, vector <int>& v){
      if(idx == v.size()) return 0;
      if(dp[idx][time] != -1) return dp[idx][time];
      int ret = INT_MIN;
      ret = max(solve(idx + 1, time, v), v[idx] * time + solve(idx
      + 1, time + 1, v));
      return dp[idx][time] = ret;
   }
   int maxSatisfaction(vector<int>& v) {
      memset(dp, -1, sizeof(dp));
      sort(v.begin(), v.end());
      return solve(0, 1, v);
   }
};
main(){
   Solution ob;
   vector<int> v = {-1,-7,0,6,-7};
   cout << (ob.maxSatisfaction(v));
}

Input

{-1,-7,0,6,-7}

Output

17

Updated on: 09-Jun-2020

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements