Best Solution|| Similar to Best time to buy & sell a stock|| 0 ms|| O(n) complexity
image.png\n\n\n## Intuition\nThe problem is to find the maximum difference between any two elements in an array nums such that the second element appears after 
image.png\n![image.png](https://assets.leetcode.com/users/images/6cb28897-672a-4437-8153-f63733893fee_1714468793.3310163.png)\n\n## Intuition\nThe problem is to find the maximum difference between any two elements in an array `nums` such that the second element appears after the first. This can be approached by iterating through the array and keeping track of the minimum element encountered so far (`current_element`) and the maximum difference (`max_difference`) found.\n\n## Approach\n1. Initialize `current_element` to be the first element of the array `nums` and `max_difference` to `0`.\n2. Iterate through the array `nums` starting from the second element.\n3. For each element `nums[i]`:\n   - Update `current_element` to be the minimum of `current_element` and `nums[i]`.\n   - Calculate the difference `nums[i] - current_element`.\n   - Update `max_difference` to be the maximum of `max_difference` and the calculated difference.\n4. After iterating through the array, if `max_difference` is still `0`, return `-1` indicating that no valid difference was found. Otherwise, return `max_difference` as the maximum difference found.\n\n## Complexity\n- Time Complexity: The algorithm has a time complexity of \\(O(n)\\), where \\(n\\) is the number of elements in the `nums` array. This is because we perform a single pass through the array to update `current_element` and `max_difference`.\n- Space Complexity: The algorithm has a space complexity of \\(O(1)\\) since we only use a constant amount of extra space for the `current_element` and `max_difference` variables, regardless of the size of the input array `nums`.\n\n```java\nclass Solution {\n    public int maximumDifference(int[] nums) {\n        int current_element = nums[0];\n        int max_difference = 0;\n        \n        for (int i = 0; i < nums.length; i++) {\n            if (nums[i] < current_element) {\n                current_element = nums[i];\n            }\n            if (nums[i] - current_element > max_difference) {\n                max_difference = nums[i] - current_element;\n            }\n        }\n        \n        if (max_difference == 0) {\n            return -1; // Return -1 if no valid difference was found\n        } else {\n            return max_difference; // Return the maximum difference found\n        }\n    }\n}\n```\n\nThis solution efficiently computes the maximum difference between any two elements in the array `nums` based on the defined constraints and returns the result accordingly. The algorithm ensures optimal time and space complexity by utilizing a single pass through the array with constant space usage.
['Array', 'Math', 'Java']