Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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. There could be different prizes at the same position on the line. You are also given an integer k.
You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.
k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4.Return the maximum number of prizes you can win if you choose the two segments optimally.
Example 1:
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].
Example 2:
Input: prizePositions = [1,2,3,4], k = 0 Output: 2 Explanation: For this example, one choice for the segments is[3, 3]and[4, 4],and you will be able to get2prizes.
Constraints:
1 <= prizePositions.length <= 1051 <= prizePositions[i] <= 1090 <= k <= 109 prizePositions is sorted in non-decreasing order.Problem summary: 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. There could be different prizes at the same position on the line. You are also given an integer k. You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect. For example if k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4. Return the maximum number of prizes you can win if you choose the two segments optimally.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Sliding Window
[1,1,2,2,3,3,5] 2
[1,2,3,4] 0
best-time-to-buy-and-sell-stock-iii)two-best-non-overlapping-events)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2555: Maximize Win From Two Segments
class Solution {
public int maximizeWin(int[] prizePositions, int k) {
int n = prizePositions.length;
int[] f = new int[n + 1];
int ans = 0;
for (int i = 1; i <= n; ++i) {
int x = prizePositions[i - 1];
int j = search(prizePositions, x - k);
ans = Math.max(ans, f[j] + i - j);
f[i] = Math.max(f[i - 1], i - j);
}
return ans;
}
private int search(int[] nums, int x) {
int left = 0, right = nums.length;
while (left < right) {
int mid = (left + right) >> 1;
if (nums[mid] >= x) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
// Accepted solution for LeetCode #2555: Maximize Win From Two Segments
func maximizeWin(prizePositions []int, k int) (ans int) {
n := len(prizePositions)
f := make([]int, n+1)
for i, x := range prizePositions {
j := sort.Search(n, func(h int) bool { return prizePositions[h] >= x-k })
ans = max(ans, f[j]+i-j+1)
f[i+1] = max(f[i], i-j+1)
}
return
}
# Accepted solution for LeetCode #2555: Maximize Win From Two Segments
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
// Accepted solution for LeetCode #2555: Maximize Win From Two Segments
/**
* [2555] Maximize Win From Two Segments
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn maximize_win(prize_positions: Vec<i32>, k: i32) -> i32 {
let n = prize_positions.len();
let mut dp = vec![0; n + 1];
let mut result = 0;
for i in 0..n {
let j = Self::binary_search(&prize_positions, prize_positions[i] - k);
result = result.max(i - j + 1 + dp[j]);
dp[i + 1] = dp[i].max(i - j + 1);
}
result as i32
}
fn binary_search(array: &Vec<i32>, target: i32) -> usize {
let (mut left, mut right) = (0, array.len());
while left < right {
let middle = left + (right - left) / 2;
if array[middle] < target {
left = middle + 1;
} else {
right = middle;
}
}
left
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2555() {
assert_eq!(7, Solution::maximize_win(vec![1, 1, 2, 2, 3, 3, 5], 2));
assert_eq!(2, Solution::maximize_win(vec![1, 2, 3, 4], 0));
}
}
// Accepted solution for LeetCode #2555: Maximize Win From Two Segments
function maximizeWin(prizePositions: number[], k: number): number {
const n = prizePositions.length;
const f: number[] = Array(n + 1).fill(0);
let ans = 0;
const search = (x: number): number => {
let left = 0;
let right = n;
while (left < right) {
const mid = (left + right) >> 1;
if (prizePositions[mid] >= x) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
};
for (let i = 1; i <= n; ++i) {
const x = prizePositions[i - 1];
const j = search(x - k);
ans = Math.max(ans, f[j] + i - j);
f[i] = Math.max(f[i - 1], i - j);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.