Skip to main content
Back to problems
#1793
Hard Algorithms

Maximum score of a good subarray

Array Two Pointers Binary Search Stack Monotonic Stack
64.4% acceptance
Feb 25, 2026
2001
50
You are given an array of integers nums and an integer k. The score of a subarray (i, j) is defined as min(nums[i..=j]) * (j - i + 1). A good subarray must satisfy i <= k <= j. Return the maximum possible score of a good subarray.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_score(nums: Vec<i32>, k: i32) -> i32 {
    let n = nums.len();
    let k = k as usize;
    let mut l = k;
    let mut r = k;
    let mut min_val = nums[k];
    let mut ans = min_val;
    while l > 0 || r < n - 1 {
      // Expand to the side with larger adjacent element
      let left_val = if l > 0 { nums[l - 1] } else { 0 };
      let right_val = if r < n - 1 { nums[r + 1] } else { 0 };
      if left_val >= right_val {
        l -= 1;
        min_val = min_val.min(nums[l]);
      } else {
        r += 1;
        min_val = min_val.min(nums[r]);
      }
      ans = ans.max(min_val * (r - l + 1) as i32);
    }
    ans
  }
}