1
var minDifficulty = function (jobDifficulty, d) {2
// don't have enought jobs to distribute3
if (jobDifficulty.length < d) {7
// in dynamic programming top-down approach8
// we need to have memoisation to not repeat calculations9
let memo = new Array(d + 1)11
.map(() => new Array(jobDifficulty.length + 1).fill(-1));13
const dp = function (D, N) {14
// if we calculated this before, just return15
if (-1 != memo[D][N]) {19
// if we have only 1 day, we just need to take all jobs20
// and return the highest difficulty23
for (let i = 0; i < N; i++) {24
if (memo[D][N] < jobDifficulty[i]) {25
memo[D][N] = jobDifficulty[i];31
// otherwise, we use our recurrence relation to calculate32
memo[D][N] = 1000 * D;34
let max_job_per_day = N - D + 1;35
let max_difficulty = 0;37
// iteration for recurrence relation38
for (let X = 1; X <= max_job_per_day; X++) {39
// count max in the current range40
// len - X is the starting point for41
// the last day in D days42
if (jobDifficulty[N - X] > max_difficulty) {43
max_difficulty = jobDifficulty[N - X];45
// recurrence relation47
// so we still have N - X jobs for D - 1 days48
let min_sum = max_difficulty + dp(D - 1, N - X);51
if (min_sum < memo[D][N]) {59
return dp(d, jobDifficulty.length);