Maximum Score of a Good Subarray — LeetCode 1793 Python Solution

HardStackArrayTwo PointersBinary SearchMonotonic Stack
Problem
#1793
Pattern
Stack
Reading time
4 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview