Maximum Difference Between Increasing Elements — LeetCode 2016 Python Solution
EasyArray
- Problem
- #2016
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [7,1,5,4]
- Output
- 4
- Explanation
- The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.
Python solution
Python
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
mi = inf
ans = -1
for x in nums:
if x > mi:
ans = max(ans, x - mi)
else:
mi = x
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 2016. Maximum Difference Between Increasing Elements?
- LeetCode 2016. Maximum Difference Between Increasing Elements is rated Easy on LeetCode.
- What topics does LeetCode 2016. Maximum Difference Between Increasing Elements cover?
- LeetCode 2016. Maximum Difference Between Increasing Elements is tagged Array on LeetCode.