Problem Description
Given an array of integers, find the maximum difference between two elements such that the smaller element appears before the larger element in the array. If no such pair exists (i.e., the array is non-increasing), return -1.
Key Insights
- Keep track of the minimum element encountered so far while iterating through the array.
- For each element, calculate the difference between the current element and the minimum element so far.
- Update the maximum difference when a greater valid difference is found.
- If no valid increasing pair exists, the result remains -1.
Space and Time Complexity
Time Complexity: O(n) (single pass through the array) Space Complexity: O(1) (only constant extra space used)
Solution
Use a single pass through the array to keep a record of the minimum element seen so far. At each step, compute the potential difference between the current element and this minimum. If the current element is greater, update the maximum difference if needed; otherwise, update the minimum element. This approach efficiently finds the maximum difference with O(n) time complexity and O(1) space complexity without requiring any extra data structures.