EasyNo. 2016

Maximum Difference Between Increasing Elements — LeetCode 2016 Python Solution

Topics
Array
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(1) to O(n)

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.

Free to download. Check it runs on your machine, then pick a plan.