Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an array of integers nums (0-indexed) and an integer k.
The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.
Return the maximum possible score of a good subarray.
Example 1:
Input: nums = [1,4,3,7,4,5], k = 3 Output: 15 Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.
Example 2:
Input: nums = [5,5,4,5,4,1,1,1], k = 0 Output: 20 Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 2 * 1040 <= k < nums.lengthProblem summary: You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Binary Search · Stack
[1,4,3,7,4,5] 3
[5,5,4,5,4,1,1,1] 0
largest-rectangle-in-histogram)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1793: Maximum Score of a Good Subarray
class Solution {
public int maximumScore(int[] nums, int k) {
int n = nums.length;
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, -1);
Arrays.fill(right, n);
Deque<Integer> stk = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
int v = nums[i];
while (!stk.isEmpty() && nums[stk.peek()] >= v) {
stk.pop();
}
if (!stk.isEmpty()) {
left[i] = stk.peek();
}
stk.push(i);
}
stk.clear();
for (int i = n - 1; i >= 0; --i) {
int v = nums[i];
while (!stk.isEmpty() && nums[stk.peek()] > v) {
stk.pop();
}
if (!stk.isEmpty()) {
right[i] = stk.peek();
}
stk.push(i);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (left[i] + 1 <= k && k <= right[i] - 1) {
ans = Math.max(ans, nums[i] * (right[i] - left[i] - 1));
}
}
return ans;
}
}
// Accepted solution for LeetCode #1793: Maximum Score of a Good Subarray
func maximumScore(nums []int, k int) (ans int) {
n := len(nums)
left := make([]int, n)
right := make([]int, n)
for i := range left {
left[i] = -1
right[i] = n
}
stk := []int{}
for i, v := range nums {
for len(stk) > 0 && nums[stk[len(stk)-1]] >= v {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
left[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
stk = []int{}
for i := n - 1; i >= 0; i-- {
v := nums[i]
for len(stk) > 0 && nums[stk[len(stk)-1]] > v {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
right[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
for i, v := range nums {
if left[i]+1 <= k && k <= right[i]-1 {
ans = max(ans, v*(right[i]-left[i]-1))
}
}
return
}
# Accepted solution for LeetCode #1793: Maximum Score of a Good Subarray
class Solution:
def maximumScore(self, nums: List[int], k: int) -> int:
n = len(nums)
left = [-1] * n
right = [n] * n
stk = []
for i, v in enumerate(nums):
while stk and nums[stk[-1]] >= v:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
stk = []
for i in range(n - 1, -1, -1):
v = nums[i]
while stk and nums[stk[-1]] > v:
stk.pop()
if stk:
right[i] = stk[-1]
stk.append(i)
ans = 0
for i, v in enumerate(nums):
if left[i] + 1 <= k <= right[i] - 1:
ans = max(ans, v * (right[i] - left[i] - 1))
return ans
// Accepted solution for LeetCode #1793: Maximum Score of a Good Subarray
/**
* [1793] Maximum Score of a Good Subarray
*
* You are given an array of integers nums (0-indexed) and an integer k.
* The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.
* Return the maximum possible score of a good subarray.
*
* Example 1:
*
* Input: nums = [1,4,3,7,4,5], k = 3
* Output: 15
* Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.
*
* Example 2:
*
* Input: nums = [5,5,4,5,4,1,1,1], k = 0
* Output: 20
* Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
*
*
* Constraints:
*
* 1 <= nums.length <= 10^5
* 1 <= nums[i] <= 2 * 10^4
* 0 <= k < nums.length
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/maximum-score-of-a-good-subarray/
// discuss: https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn maximum_score(nums: Vec<i32>, k: i32) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1793_example_1() {
let nums = vec![1, 4, 3, 7, 4, 5];
let k = 3;
let result = 15;
assert_eq!(Solution::maximum_score(nums, k), result);
}
#[test]
#[ignore]
fn test_1793_example_2() {
let nums = vec![5, 5, 4, 5, 4, 1, 1, 1];
let k = 0;
let result = 20;
assert_eq!(Solution::maximum_score(nums, k), result);
}
}
// Accepted solution for LeetCode #1793: Maximum Score of a Good Subarray
function maximumScore(nums: number[], k: number): number {
const n = nums.length;
const left: number[] = Array(n).fill(-1);
const right: number[] = Array(n).fill(n);
const stk: number[] = [];
for (let i = 0; i < n; ++i) {
while (stk.length && nums[stk.at(-1)] >= nums[i]) {
stk.pop();
}
if (stk.length) {
left[i] = stk.at(-1);
}
stk.push(i);
}
stk.length = 0;
for (let i = n - 1; ~i; --i) {
while (stk.length && nums[stk.at(-1)] > nums[i]) {
stk.pop();
}
if (stk.length) {
right[i] = stk.at(-1);
}
stk.push(i);
}
let ans = 0;
for (let i = 0; i < n; ++i) {
if (left[i] + 1 <= k && k <= right[i] - 1) {
ans = Math.max(ans, nums[i] * (right[i] - left[i] - 1));
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.