Maximize Win From Two Segments — LeetCode 2555 Python Solution

MediumArrayBinary SearchSliding Window
Problem
#2555
Reading time
2 min

The problem

There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize.

Example

Input
prizePositions = [1,1,2,2,3,3,5], k = 2
Output
7
Explanation
In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5].

Python solution

Python
class Solution:
    def maximizeWin(self, prizePositions: List[int], k: int) -> int:
        n = len(prizePositions)
        f = [0] * (n + 1)
        ans = 0
        for i, x in enumerate(prizePositions, 1):
            j = bisect_left(prizePositions, x - k)
            ans = max(ans, f[j] + i - j)
            f[i] = max(f[i - 1], i - j)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2555. Maximize Win From Two Segments is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2555. Maximize Win From Two Segments?
LeetCode 2555. Maximize Win From Two Segments is rated Medium on LeetCode.
What is the time complexity of LeetCode 2555. Maximize Win From Two Segments?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2555. Maximize Win From Two Segments?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2555. Maximize Win From Two Segments cover?
LeetCode 2555. Maximize Win From Two Segments is tagged Array, Binary Search and Sliding Window 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