HardNo. 1793
Maximum Score of a Good Subarray — LeetCode 1793 Python Solution
- Pattern
- Stack
- Topics
- Stack, Array, Two Pointers, Binary Search, Monotonic Stack
- Reading time
- 4 min
- Source
- leetcode.com
The 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).
Example
- 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.
Python solution
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1793. Maximum Score of a Good Subarray is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1574 | Shortest Subarray to be Removed to Make Array Sorted | Medium |
| 0042 | Trapping Rain Water | Hard |
| 0321 | Create Maximum Number | Hard |
| 0581 | Shortest Unsorted Continuous Subarray | Medium |
| 0962 | Maximum Width Ramp | Medium |
| 0143 | Reorder List | Medium |
Frequently asked questions
- How hard is LeetCode 1793. Maximum Score of a Good Subarray?
LeetCode 1793. Maximum Score of a Good Subarray is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1793. Maximum Score of a Good Subarray?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1793. Maximum Score of a Good Subarray?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1793. Maximum Score of a Good Subarray cover?
LeetCode 1793. Maximum Score of a Good Subarray is tagged Stack, Array, Two Pointers, Binary Search and Monotonic Stack on LeetCode.