Given an integer array nums, find the maximum value of j-i such that nums[j] > nums[i].

For example,

Input:  [9, 10, 2, 6, 7, 12, 8, 1]
Output: 5
Explanation: The maximum difference is 5 for i = 0, j = 5
 
Input:  [9, 2, 1, 6, 7, 3, 8]
Output: 5
Explanation: The maximum difference is 5 for i = 1, j = 6
 
Input:  [8, 7, 5, 4, 2, 1]
Output: -INF
Explanation: Array is sorted in decreasing order.

Practice this problem

1. Brute-Force Solution

A simple solution is to use two loops. For each element, check the greater elements to its right and keep track of the maximum value of j-i. The time complexity of this solution is O(n2), where n is the size of the input.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The maximum value is 5

Java


Download  Run Code

Output:

The maximum value is 5

Python


Download  Run Code

Output:

The maximum value is 5

2. O(n) solution using extra space

The idea is to construct an auxiliary array aux, where aux[j] stores the maximum element in subarray nums[j…n-1]. Then traverse the auxiliary array aux from left to right along with the input array nums to find the greatest j-i value, as demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum value is 5

Java


Download  Run Code

Output:

The maximum value is 5

Python


Download  Run Code

Output:

The maximum value is 5

The time complexity of the above solution is O(n), and the auxiliary space used by the program is O(n).