Skip to main content
Back to problems
#2874
Medium Algorithms

Maximum value of an ordered triplet ii

Array
56.4% acceptance
Feb 25, 2026
826
20
You are given a 0-indexed integer array nums. Return the maximum value over all triplets of indices (i, j, k) such that i < j < k. If all such triplets have a negative value, return 0. The value of a triplet of indices (i, j, k) is equal to (nums[i] - nums[j]) * nums[k].

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_triplet_value(nums: Vec<i32>) -> i64 {
    let n = nums.len();
    // For each k, maximize (max_i - min_j) for i < j < k
    // Maintain prefix max and max (prefix_max - nums[j])
    let mut ans = 0i64;
    let mut max_i = 0i64; // max nums[i] for i < j
    let mut max_diff = 0i64; // max (nums[i] - nums[j]) for i < j < k
    for k in 0..n {
      ans = ans.max(max_diff * nums[k] as i64);
      max_diff = max_diff.max(max_i - nums[k] as i64);
      max_i = max_i.max(nums[k] as i64);
    }
    ans
  }
}