Leetcode 2016. Maximum Difference Between Increasing Elements
Given a 0-indexed integer array nums
of size n
, you need to 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
exist, return -1
.
n
) can go up to 10^4
.nums[j] > nums[i]
.-1
would be appropriate since finding such pairs is not possible.min_element
to keep track of the minimum element seen so far and set it to nums[0]
.max_diff
to keep the maximum difference found and set it to -1
.min_element
.
max_diff
with the maximum of max_diff
and (current_element
- min_element
).min_element
if the current element is smaller.max_diff
.nums
, since we only need a single pass through the array.public class Solution {
public int maximumDifference(int[] nums) {
if (nums == null || nums.length < 2) {
return -1;
}
int min_element = nums[0];
int max_diff = -1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > min_element) {
max_diff = Math.max(max_diff, nums[i] - min_element);
} else {
min_element = nums[i];
}
}
return max_diff;
}
public static void main(String[] args) {
Solution sol = new Solution();
int result = sol.maximumDifference(new int[]{7, 1, 5, 4});
System.out.println(result); // Output should be 4 (5 - 1)
}
}
min_element
to the first element and max_diff
to -1
.min_element
, update max_diff
. Otherwise, update min_element
.max_diff
. If no valid i, j
pairs were found, max_diff
remains -1
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?