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.
Input: nums =[7,1̲,5̲,4]Output: 4Explanation:
The maximum difference occurs with i =1 and j =2, nums[j]- nums[i]=5-1=4.Note that with i =1 and j =0, the difference nums[j]- nums[i]=7-1=6, but i > j, so it is not valid.
Intuition:
To maximize the difference nums[j] - nums[i] with i < j and nums[i] < nums[j], keep track of the smallest value seen so far as you iterate. For each element, compute the difference with the minimum so far if it’s greater, and update the answer.
Approach:
Initialize ans to -1 and min_val to the first element.
Iterate through the array from the second element:
If the current element is greater than min_val, update ans with the maximum of ans and the difference.
classSolution {
public:int maximumDifference(vector<int>& nums) {
int ans =-1, min_val = nums[0];
for (int i =1; i < nums.size(); ++i) {
if (nums[i] > min_val)
ans = max(ans, nums[i] - min_val);
else min_val = nums[i];
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
funcmaximumDifference(nums []int) int {
ans:=-1minVal:=nums[0]
fori:=1; i < len(nums); i++ {
ifnums[i] > minVal {
ifnums[i]-minVal > ans {
ans = nums[i] -minVal }
} else {
minVal = nums[i]
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintmaximumDifference(int[] nums) {
int ans =-1, minVal = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i]> minVal)
ans = Math.max(ans, nums[i]- minVal);
else minVal = nums[i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaximumDifference(nums: IntArray): Int {
var ans = -1var minVal = nums[0]
for (i in1 until nums.size) {
if (nums[i] > minVal)
ans = maxOf(ans, nums[i] - minVal)
else minVal = nums[i]
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defmaximumDifference(self, nums: list[int]) -> int:
ans: int =-1 min_val: int = nums[0]
for num in nums[1:]:
if num > min_val:
ans = max(ans, num - min_val)
else:
min_val = num
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnmaximum_difference(nums: Vec<i32>) -> i32 {
letmut ans =-1;
letmut min_val = nums[0];
for&num in nums.iter().skip(1) {
if num > min_val {
ans = ans.max(num - min_val);
} else {
min_val = num;
}
}
ans
}
}