Skip to main content
Back to problems
#2016
Easy Algorithms

Maximum difference between increasing elements

Array
66.5% acceptance
Feb 25, 2026
1511
44
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_difference(nums: Vec<i32>) -> i32 {
    let mut min_so_far = nums[0];
    let mut ans = -1;
    for &x in &nums[1..] {
      if x > min_so_far {
        ans = ans.max(x - min_so_far);
      } else {
        min_so_far = min_so_far.min(x);
      }
    }
    ans
  }
}