Beats 100% || easy || 0ms solution...
IntuitionThe problem requires finding the maximum difference between two elements in the list such that the larger element appears after the smaller element.
A
# Intuition
The problem requires finding the maximum difference between two elements in the list such that the larger element appears after the smaller element.  
A naive approach would be to check every pair, but we can optimize by keeping track of the minimum element encountered so far while iterating.

![image.png](https://assets.leetcode.com/users/images/704753bd-5391-4ac5-adb3-2eef22c83931_1743003028.083983.png)


# Approach
- Initialize `max_diff` as `0` and `min_elem` as the first element of `nums`.
- Iterate through `nums`, updating `max_diff` as the maximum difference found so far.
- Also, update `min_elem` to keep track of the smallest element encountered so far.
- If `max_diff` remains `0`, return `-1` since no valid difference exists.

# Complexity
- **Time complexity:** $$O(n)$$  
  Since we only iterate through the list once, the time complexity is linear.

- **Space complexity:** $$O(1)$$  
  We only use a few extra variables, so the space complexity is constant.

# Code
```python []

class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        max_diff = 0
        min_elem = nums[0]

        for i in nums:
            max_diff = max(max_diff, i - min_elem)
            min_elem = min(min_elem, i)

        return max_diff if max_diff > 0 else -1
```
```c []
int maximumDifference(int nums[], int size) {
    int max_diff = -1, min_elem = nums[0];

    for (int i = 1; i < size; i++) {
        if (nums[i] > min_elem) {
            max_diff = (nums[i] - min_elem > max_diff) ? nums[i] - min_elem : max_diff;
        }
        if (nums[i] < min_elem) {
            min_elem = nums[i];
        }
    }

    return max_diff;
}
```
```C++ []
class Solution {
public:
    int maximumDifference(vector<int>& nums) {
        int max_diff = -1, min_elem = nums[0];

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

        return max_diff;
    }
};
```
``` Java []
class Solution {
    public int maximumDifference(int[] nums) {
        int max_diff = -1, min_elem = nums[0];

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

        return max_diff;
    }
}
```

['Array', 'C', 'Python', 'C++', 'Java', 'Python3']