Maximum Difference Between Increasing Elements — LeetCode 2016 Python Solution

EasyArray
Problem
#2016
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview