Stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { public int maximumScore(int[] nums, int k) { Stack<Integer> increaseStack = new Stack<>();
int[] left = new int[nums.length]; for (int i = 0; i < nums.length; i++) { while (!increaseStack.isEmpty() && nums[i] <= nums[increaseStack.peek()]) { increaseStack.pop(); }
left[i] = increaseStack.isEmpty() ? -1 : increaseStack.peek(); increaseStack.push(i); }
increaseStack.clear();
int[] right = new int[nums.length]; for (int i = nums.length - 1; i >= 0; i--) { while (!increaseStack.isEmpty() && nums[i] <= nums[increaseStack.peek()]) { increaseStack.pop(); }
right[i] = increaseStack.isEmpty() ? nums.length : increaseStack.peek(); increaseStack.push(i); }
int maxScore = 0; for (int i = 0; i < nums.length; i++) { int leftIndex = left[i], rightIndex = right[i]; if (leftIndex < k && k < rightIndex) { maxScore = Math.max(maxScore, nums[i] * (rightIndex - leftIndex - 1)); } }
return maxScore; } }
|
Two Pointers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int maximumScore(int[] nums, int k) { int n = nums.length;
int maxScore = nums[k]; int i = k, j = k, minHeight = nums[k];
int times = n - 1; while (times > 0) { if (j == n - 1 || (i > 0 && nums[i - 1] > nums[j + 1])) { i--; minHeight = Math.min(minHeight, nums[i]); } else { j++; minHeight = Math.min(minHeight, nums[j]); }
maxScore = Math.max(maxScore, minHeight * (j - i + 1)); times--; }
return maxScore; } }
|
References
1793. Maximum Score of a Good Subarray