Given a 0-indexed integer array nums
of size n
, 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
exists, return -1
.
For example:
nums = [7,1,5,4]
should return 4
nums = [9,4,3,2]
should return -1
nums = [1,5,2,10]
should return 9
## Maximum Difference Between Increasing Elements
### Problem Description
Given a **0-indexed** integer array `nums` of size `n`, the goal is 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]`. If no such `i` and `j` exist, return `-1`.
### Naive Solution
A brute-force approach involves iterating through all possible pairs `(i, j)` such that `i < j`, checking if `nums[i] < nums[j]`, and updating the maximum difference accordingly. This approach has a time complexity of O(n^2).
```python
def maximumDifference_naive(nums):
max_diff = -1
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] < nums[j]:
max_diff = max(max_diff, nums[j] - nums[i])
return max_diff
A more efficient approach is to iterate through the array once, keeping track of the minimum element seen so far. For each element nums[j]
, we check if it's greater than the minimum element seen before nums[i]
. If it is, we update the maximum difference. This approach has a time complexity of O(n).
def maximumDifference_optimal(nums):
max_diff = -1
min_element = nums[0]
for j in range(1, len(nums)):
if nums[j] > min_element:
max_diff = max(max_diff, nums[j] - min_element)
else:
min_element = nums[j] # Update min_element if a smaller number is found
return max_diff
For nums = [7, 1, 5, 4]
, the optimal solution works as follows:
max_diff = -1
and min_element = 7
.j = 1
, nums[j] = 1
. Since 1 < 7
, update min_element = 1
.j = 2
, nums[j] = 5
. Since 5 > 1
, update max_diff = max(-1, 5 - 1) = 4
.j = 3
, nums[j] = 4
. Since 4 > 1
, update max_diff = max(4, 4 - 1) = 4
.max_diff = 4
.The optimal solution iterates through the array once. Therefore, the time complexity is O(n), where n is the number of elements in the array. The naive solution has nested loops, resulting in O(n^2) time complexity.
The optimal solution uses a constant amount of extra space to store max_diff
and min_element
. Therefore, the space complexity is O(1), which means it's constant and doesn't depend on the size of the input array.
i < j
, so the algorithm should return -1. Note that based on the constraints in the problem statement, the length of nums
will always be between 2 and 1000 (inclusive), so we don't have to handle arrays of length 0 or 1.[9, 4, 3, 2]
), there will be no i
and j
such that nums[i] < nums[j]
. The algorithm should return -1.[5, 5, 5, 5]
), the algorithm will also return -1 because no i
and j
will satisfy nums[i] < nums[j]
.The provided optimal solution correctly handles all these cases.