[LeetCode] Maximum Difference Between Increasing Elements

2016. Maximum Difference Between Increasing Elements

Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].

Return the maximum difference. If no such i and j exists, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int res = -1;
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
if(nums[j] > nums[i]) res = max(res, nums[j] - nums[i]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/16/PS/LeetCode/maximum-difference-between-increasing-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.