# Program to find minimum sum of difficulties to complete jobs over k days in C++

Suppose we have a list of numbers called jobs and another value k. Now we want to finish all jobs in k different days. The jobs must be performed in the given order and in each day we have to complete one task. The difficulty of job i is stored at jobs[i] and the difficulty of completing a list of jobs on a day will be the maximum difficulty job performed on that day. So we have to find the minimum sum of the difficulties to perform the jobs over k different days.

So, if the input is like jobs = [2, 3, 4, 6, 3] k = 2, then the output will be 8, at first we do [2] then do [3, 4, 6, 3]. so the difficulty is 2 + maximum of (3, 4, 6, 3) = 8.

To solve this, we will follow these steps −

• Define an array dp of size: 505 x 15.
• Define a function dfs(), this will take start, k, and an array v,
• if start >= size of v, then −
• return (if k is same as 0, then 0, otherwise inf)
• if k < 0, then −
• return inf
• if dp[start, k] is not equal to -1, then −
• return dp[start, k]
• ret := inf
• val := 0
• for initialize i := start, when i < size of v, update (increase i by 1), do −
• val := maximum of val and v[i]
• ret := minimum of ret and (val + dfs(i + 1, k - 1, v))
• dp[start, k] = ret
• return ret
• From the main method do the following −
• fill dp with -1
• return dfs(0, k, jobs)

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
const int inf = 1e6;
int dp[505][15];
int dfs(int start, int k, vector <int>& v){
if(start >= v.size()){
return k == 0 ? 0 : inf;
}
if(k < 0)
return inf;
if(dp[start][k] != -1)
return dp[start][k];
int ret = inf;
int val = 0;
for(int i = start; i < v.size(); i++){
val = max(val, v[i]);
ret = min(ret, val + dfs(i + 1, k - 1, v));
}
return dp[start][k] = ret;
}
int solve(vector<int>& jobs, int k) {
memset(dp ,-1, sizeof dp);
return dfs(0, k, jobs);
}
int main(){
vector<int> v = {2, 3, 4, 6, 3};
int k = 2;
cout << solve(v, k);
}

## Input

{2, 3, 4, 6, 3}, 2

## Output

8

Advertisements