Maximum Score of a Good Subarray - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,4,3,7,4,5], k = 3
›
Output:
15
💡 Note:
The optimal subarray is [3,7,4] from index 2 to 4. Minimum value is 3, length is 3, so score = 3 × 3 = 9. Actually, [7] gives score 7×1=7, but [3,7] gives 3×2=6, [3,7,4] gives 3×3=9, [7,4] gives 4×2=8, [7,4,5] gives 4×3=12, [3,7,4,5] gives 3×4=12, [4,3,7,4,5] gives 3×5=15.
Example 2 — Single Element Best
$
Input:
nums = [5,5,4,5,4,1,1,1], k = 0
›
Output:
20
💡 Note:
k=0, so we must include nums[0]=5. The best subarray is [5,5,4,5] from index 0 to 3, with minimum 4 and length 4, giving score = 4 × 4 = 16. Wait, [5,5] gives 5×2=10, [5,5,4,5] gives 4×4=16, [5,5,4,5,4] gives 4×5=20.
Example 3 — Edge Position
$
Input:
nums = [1,4,3,7,4,5], k = 5
›
Output:
15
💡 Note:
k=5 (last position), nums[5]=5. We expand left: [5] score=5, [4,5] score=8, [7,4,5] score=12, [3,7,4,5] score=12, [4,3,7,4,5] score=15, [1,4,3,7,4,5] score=6. Maximum is 15.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 2 × 104
- 0 ≤ k < nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,4,3,7,4,5] with k=3
2
Process
Find subarray containing index 3 with max(min × length)
3
Output
Maximum score is 15 from subarray [1,4,3,7,4]
Key Takeaway
🎯 Key Insight: Use greedy two-pointer expansion from k toward higher values to maximize score efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code