Skip to main content
Back to problems
#3584
Medium Algorithms

Maximum product of first and last elements of a subsequence

Array Two Pointers
31.2% acceptance
Feb 25, 2026
113
1
Maximum product of first and last elements of a subsequence of length m. The subsequence preserves order; product = nums[i] * nums[j] for j - i >= m - 1.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_product(nums: Vec<i32>, m: i32) -> i64 {
    let n = nums.len();
    let m = m as usize;
    // For each j from m-1 to n-1, valid i in 0..=(j-(m-1))
    // As j increases by 1, window of valid i grows by 1 (adds i = j - m + 1).
    // Track the max and min of nums[i] in the window to maximize product.
    let mut max_left = i64::MIN;
    let mut min_left = i64::MAX;
    let mut ans = i64::MIN;

    for j in (m - 1)..n {
      // new valid i = j - (m - 1)
      let new_i = j - (m - 1);
      let v = nums[new_i] as i64;
      if v > max_left { max_left = v; }
      if v < min_left { min_left = v; }

      let nj = nums[j] as i64;
      let p1 = max_left * nj;
      let p2 = min_left * nj;
      let best = p1.max(p2);
      if best > ans { ans = best; }
    }

    ans
  }
}