Skip to main content
Back to problems
Leetcode
Easy
Arrays
Greedy
Maximum Difference Between Increasing Elements

Find the largest difference nums[j] - nums[i] where i < j and nums[i] < nums[j].

Acceptance 100%
Problem Statement

Given an integer array nums, choose two indices i and j such that 0 <= i < j < nums.length and nums[i] < nums[j]. Among all such valid pairs, return the maximum value of nums[j] - nums[i]. If no valid pair exists, return -1.

The task is to identify the best increasing pair, not necessarily adjacent, and compute the largest positive difference.

Input Format

  • A single integer array nums.
  • nums contains at least two elements.

Output Format

  • Return an integer representing the maximum difference nums[j] - nums[i] over all valid pairs with i < j and nums[i] < nums[j].
  • If no such pair exists, return -1.

Constraints

  • 2 <= nums.length
  • The answer should be based on indices i < j
  • Only pairs with nums[i] < nums[j] are valid
  • If no valid increasing pair exists, return -1
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [7,1,5,4]

Output

4

Explanation

The best valid pair is (1, 5), giving a difference of 4.

Example 2

Input

nums = [9,4,3,2]

Output

-1

Explanation

There is no pair i < j with nums[i] < nums[j].

Show 1 more example

Example 3

Input

nums = [1,5,2,10]

Output

9

Explanation

The best valid pair is (1, 10), giving a difference of 9.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.