#1793

Maximum Score of a Good Subarray

Hard
ArrayTwo PointersBinary SearchStackMonotonic StackMonotonic StackTwo PointersSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a monotonic stack to efficiently find the maximum score by determining the range of subarrays that can include the index k. This approach reduces the time complexity significantly by avoiding the need to check every subarray explicitly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a stack to keep track of indices and a variable for the maximum score.
  2. 2Step 2: Iterate through the array to find the left and right bounds for each element using the stack.
  3. 3Step 3: For each element, calculate the score using its minimum value and the length of the valid subarray that includes k.
  4. 4Step 4: Update the maximum score if the current score is higher.
solution.py34 lines
1# Full working Python code
2
3def maxScore(nums, k):
4    n = len(nums)
5    left = [0] * n
6    right = [0] * n
7    stack = []
8
9    # Calculate left bounds
10    for i in range(n):
11        while stack and nums[stack[-1]] >= nums[i]:
12            stack.pop()
13        left[i] = stack[-1] if stack else -1
14        stack.append(i)
15
16    stack.clear()
17
18    # Calculate right bounds
19    for i in range(n - 1, -1, -1):
20        while stack and nums[stack[-1]] > nums[i]:
21            stack.pop()
22        right[i] = stack[-1] if stack else n
23        stack.append(i)
24
25    max_score = 0
26
27    # Calculate scores
28    for i in range(n):
29        if left[i] < k < right[i]:
30            length = right[i] - left[i] - 1
31            score = nums[i] * length
32            max_score = max(max_score, score)
33
34    return max_score

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times (once for left bounds and once for right bounds). The space complexity is O(n) due to the additional arrays for left and right bounds.

  • 1The minimum value in a subarray heavily influences the score.
  • 2Using a monotonic stack allows us to efficiently find valid subarray bounds.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.