Maximum Score of a Good Subarray LeetCode solution in JavaScript

1
/*
2

3
JAVASCRIPT
4

5
*/
6
var maximumScore = function (nums, k) {
7
// iterate to the left to update the minimum value at each index
8
let min = nums[k];
9
for (let i = k - 1; i >= 0; i--) {
10
min = Math.min(min, nums[i]);
11
nums[i] = min;
12
}
13

14
// iterate to the right to update the minimum value at each index
15
min = nums[k];
16
for (let i = k + 1; i < nums.length; i++) {
17
min = Math.min(min, nums[i]);
18
nums[i] = min;
19
}
20

21
// start with 2 pointers at opposite ends of nums
22
let left = 0;
23
let right = nums.length - 1;
24
let bestScore = 0;
25

26
while (left <= right) {
27
bestScore = Math.max(
28
bestScore,
29
Math.min(nums[left], nums[right]) * (right - left + 1)
30
);
31

32
// first to check if either pointer is at k
33
// if it is at k then we must move the other pointer inwards
34
if (left === k) {
35
right--;
36
} else if (right === k) {
37
left++;
38

39
// if neither index is at k move the pointer
40
// that is smaller inwards
41
} else if (nums[left] < nums[right]) {
42
left++;
43
} else {
44
right--;
45
}
46
}
47
return bestScore;
48
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0