Given an integer array nums, choose indices i and j such that i < j and nums[i] < nums[j]. Define the value of this pair as nums[j] - nums[i].
Return the maximum possible value over all valid pairs. If no valid pair exists, return −1.
Constraints:
Input: nums = [7, 1, 5, 4]-List[int]
Output: 4-int
Explanation: The best valid pair is i = 1 (nums[i] = 1) and j = 2 (nums[j] = 5), giving 5 - 1 = 4, and no other increasing pair yields a larger difference.
Input: nums = [9, 4, 3, 2]-List[int]
Output: -1-int
Explanation: There is no pair (i, j) with i < j and nums[i] < nums[j] because the array is strictly decreasing.
Input: nums = [1, 2, 10, 3, 8]-List[int]
Output: 9-int
Explanation: Choosing i = 0 (1) and j = 2 (10) gives 10 - 1 = 9, which is the maximum possible.
Input: nums = [5, 5, 5, 6]-List[int]
Output: 1-int
Explanation: Equal elements don’t qualify (nums[i] < nums[j] is required), so the best pair is any 5 before 6, giving 6 - 5 = 1.
Input: nums = [2, 1, 2, 1, 2]-List[int]
Output: 1-int
Explanation: Tracking the smallest value seen so far (1) and maximizing nums[j] - min_so_far gives the best difference of 2 - 1 = 1.
Now, let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem: