Skip to main content
Back to problems
#2555
Medium Algorithms

Maximize win from two segments

Array Binary Search Sliding Window
37.4% acceptance
Feb 25, 2026
603
63
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn maximize_win(prize_positions: Vec<i32>, k: i32) -> i32 {
    let n = prize_positions.len();
    // dp[i] = max prizes from one segment covering only prizes at indices 0..=i-1
    let mut dp = vec![0i32; n + 1];
    let mut left = 0usize;
    let mut ans = 0;
    for right in 0..n {
      // Advance left so prize_positions[right] - prize_positions[left] <= k
      while prize_positions[right] - prize_positions[left] > k {
        left += 1;
      }
      let window = (right - left + 1) as i32;
      dp[right + 1] = dp[right].max(window);
      // Combine: segment ending at right + best segment covering 0..left-1
      ans = ans.max(dp[left] + window);
    }
    ans
  }
}