Skip to content

2016. Maximum Difference Between Increasing Elements 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int maximumDifference(vector<int>& nums) {
    int ans = -1;
    int mn = nums[0];

    for (int i = 1; i < nums.size(); ++i) {
      if (nums[i] > mn)
        ans = max(ans, nums[i] - mn);
      mn = min(mn, nums[i]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int maximumDifference(int[] nums) {
    int ans = -1;
    int mn = nums[0];

    for (int i = 1; i < nums.length; ++i) {
      if (nums[i] > mn)
        ans = Math.max(ans, nums[i] - mn);
      mn = Math.min(mn, nums[i]);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def maximumDifference(self, nums: list[int]) -> int:
    ans = -1
    mn = nums[0]

    for i in range(len(nums)):
      if nums[i] > mn:
        ans = max(ans, nums[i] - mn)
      mn = min(mn, nums[i])

    return ans