Given a 0-indexed integer array nums of size n, find the maximum difference between any two increasing elements nums[j] - nums[i] where i < j and nums[i] < nums[j].
If no such pair exists, return -1.
An increasing element means that nums[i] < nums[j] for indices i < j.
n == nums.length2 <= n <= 10001 <= nums[i] <= 10^9Use two pointers to track the minimum element seen so far and find the maximum difference with later elements.
Algorithm:
left = 0 and right = 1max = -1 to store maximum differenceright < nums.length and left < nums.length:
    nums[left] < nums[right]: calculate difference and update maxnums[left] >= nums[right]: move left to right (new minimum candidate)rightmaxExample Input: nums = [7, 1, 5, 4]
Step-by-step execution:
Result: 4
class Solution {
    public int maximumDifference(int[] nums) {
        int max = -1;
        int left = 0;
        int right = 1;
        while (right < nums.length && left < nums.length) {
            if (nums[left] < nums[right]) {
                int diff = nums[right] - nums[left];
                max = Math.max(max, diff);
            } else {
                left = right; // move left to the new minimum
            }
            right++;
        }
        return max;
    }
}
Track the minimum element seen so far and calculate the maximum difference with each subsequent element.
Algorithm:
min = nums[0] and max = -1min = min(min, nums[i])min < nums[i], calculate difference and update maxmaxExample Input: nums = [7, 1, 5, 4]
Step-by-step execution:
Result: 4
Why this works:
class Solution {
    public int maximumDifference(int[] nums) {
        int min = nums[0];
        int max = -1;
        for(int i = 1; i < nums.length; i++){
            min = Math.min(min, nums[i]);
            if(min < nums[i]){
                max = Math.max(max, nums[i] - min);
            }
        }
        return max;
    }
}
| Approach | Time Complexity | Space Complexity | Readability | Intuition | 
|---|---|---|---|---|
| Two-Pointer | O(n) | O(1) | Medium | Tracks minimum with pointers | 
| Track Minimum | O(n) | O(1) | High | Explicitly tracks minimum | 
Key Insight: Both approaches solve the same problem: find the maximum nums[j] - nums[i] where i < j and nums[i] < nums[j].
Edge Cases:
Why O(n) is optimal: We must examine each element at least once to find the global minimum and maximum difference.
Alternative Brute Force (O(n²)):
for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
        if (nums[j] > nums[i]) {
            max = Math.max(max, nums[j] - nums[i]);
        }
    }
}
This works but is too slow for n ≤ 1000.