Maximum Score from Performing Multiplication Operations LeetCode solution in JavaScript

1
/**
2
* @param {number[]} nums
3
* @param {number[]} multipliers
4
* @return {number}
5
*/
6
var maximumScore = function (nums, multipliers) {
7
// using an array as memo will be faster
8
// in processing than using an object
9
let memo = new Array(multipliers.length + 1)
10
.fill(0)
11
.map(() => new Array(multipliers.length + 1).fill(0));
12

13
// starting point will be from the end
14
for (let i = multipliers.length - 1; i >= 0; i--) {
15
// at state i, used i elements from nums
16
// and left nums.length - i consecutive elements
17
// those consecutive elements can be seen as the rest block
18
// the left of the rest block can be any where from i to 0
19
// whereas the left element that this state can use is from the rest block
20
// so left = i to 0;
21
for (let left = i; left >= 0; left--) {
22
let right = nums.length - 1 - (i - left);
23

24
// calculate all possible cases for state i
25
// each case will combine with each case of state i - 1 and so on
26
memo[i][left] = Math.max(
27
multipliers[i] * nums[left] + memo[i + 1][left + 1],
28
multipliers[i] * nums[right] + memo[i + 1][left]
29
);
30
}
31
}
32

33
// finish the calculation and
34
// return the last case that we calculated
35
return memo[0][0];
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0