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
Maximum Score of a Good Subarray INPUT nums array (k = 3) 1 i=0 4 i=1 3 i=2 7 k=3 4 i=4 5 i=5 Good Subarray Rule: i <= k <= j (must include index k=3) Score Formula: min(subarray) * length Input Values: nums = [1,4,3,7,4,5] k = 3 ALGORITHM STEPS (Greedy Two-Pointer) 1 Initialize Pointers left = k, right = k min_val = nums[k] = 7 2 Expand Greedily Choose larger neighbor to maximize min_val 3 Calculate Score score = min_val * (r-l+1) Update max if better 4 Repeat Until Done Stop when boundaries reach array limits Expansion Trace: [3,3]: min=7, score=7*1=7 [3,4]: min=4, score=4*2=8 [3,5]: min=4, score=4*3=12 [1,5]: min=3, score=3*5=15 FINAL RESULT Best Good Subarray: [1,5] 1 4 3 MIN 7 4 5 subarray length = 5 Score Calculation: min(4,3,7,4,5) = 3 length = 5 - 1 + 1 = 5 score = 3 * 5 = 15 OUTPUT 15 OK - Maximum Score Found! Good subarray: i=1, j=5 Key Insight: The greedy approach always expands toward the larger neighbor to maintain the highest possible minimum value. Starting from index k guarantees a valid "good" subarray. Expanding greedily maximizes score at each step. Time Complexity: O(n) - each element visited at most once. Space Complexity: O(1) - only pointers used. TutorialsPoint - Maximum Score of a Good Subarray | Greedy Approach
Asked in
Amazon 25 Google 20 Facebook 15
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen