Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created June 17, 2025 02:05
Show Gist options
  • Save Ifihan/f743ab1cda05db7457000cfe917d853c to your computer and use it in GitHub Desktop.
Save Ifihan/f743ab1cda05db7457000cfe917d853c to your computer and use it in GitHub Desktop.
Maximum Difference Between Increasing Elements

Question

Approach

I keep track of the smallest value seen so far as I iterate through the array. For each element, I check if it’s greater than this minimum value. If it is, I compute the difference and update the maximum difference found so far. If it’s not, I update the minimum value.

Implementation

class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        min_val = nums[0]
        max_diff = -1

        for num in nums[1:]:
            if num > min_val:
                max_diff = max(max_diff, num - min_val)
            else:
                min_val = num

        return max_diff

Complexities

  • Time: O(n)
  • Space: O(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment