![]() |
VOOZH | about |
Given an array arr[] of n positive integers, the task is to find the maximum of j - i subjected to the constraint of arr[i] <= arr[j] and i <= j.
Examples :
Input: arr[] = [34, 8, 10, 3, 2, 80, 30, 33, 1]
Output: 6
Explanation: for i = 1 and j = 7.Input: arr[] = [1, 2, 3, 4, 5, 6]
Output: 5
Explanation: For i = 0 and j = 5, arr[j] >= arr[i] and j - i is maximumInput: [6, 5, 4, 3, 2, 1]
Output: 0
Explanation: Take any i and j where i == j.
Table of Content
The idea is to use a nested loop approach where for each element in the array, we compare it with every subsequent element to check if the condition
arr[i] <= arr[j]is satisfied. If the condition is met, we calculate the difference between the indicesjandiand keep track of the maximum difference found.
6
The idea is to precompute minimum values from left to right and maximum values from right to left, then use a two-pointer approach to find the maximum valid distance. By having these preprocessed arrays, we can efficiently check if the condition arr[i] <= arr[j] is satisfied without examining every possible pair, allowing us to incrementally search for the largest possible j-i difference.
Step by step approach:
Illustration:
Let's consider the array [34, 8, 10, 3, 2, 80, 30, 33, 1]:
- First we build lMin array (minimum values from left to right):
- [34, 8, 8, 3, 2, 2, 2, 2, 1]
- Then we build rMax array (maximum values from right to left):
- [80, 80, 80, 80, 80, 80, 33, 33, 1]
- Starting with i=0, j=0: lMin[0]=34, rMax[0]=80,
- condition is satisfied (34≤80), record diff=0, increment j
- At i=0, j=5: lMin[0]=34, rMax[5]=80, max diff=5,
- increment j
- Continue until i=1, j=8: lMin[1]=8, rMax[8]=1,
- condition fails (8>1), increment i
- At i=4, j=7: lMin[4]=2, rMax[7]=33,
- condition satisfied (2≤33), max diff=3, increment j
- Final result: When we've exhausted all valid combinations, the maximum difference found is 7 (occurring when i=1, j=8 - the difference right before condition failed)
6
The idea is to optimize the previous two-array approach by eliminating the need for the lMin array and instead dynamically updating a single lMin variable while maintaining the two-pointer technique of finding the maximum index difference.
6
The idea is to use a stack to maintain indices of potential minimum elements from left to right, then traverse the array from right to left to find the maximum index difference. By carefully managing the stack and comparing elements, we can efficiently identify the largest valid j-i difference where arr[i] <= arr[j].
Step by step approach:
6