![]() |
VOOZH | about |
Given an array arr[]. Replace every element with the next greatest element (the greatest element on its right side) in the array.
Note: There is no element next to the last element, so replace it with -1.
Examples:
Input: arr[] = [16, 17, 4, 3, 5, 2]
Output: [17, 5, 5, 5, 2, -1]
Explanation: For 16 the greatest element on its right is 17 similarly for 17 it's 5 and also for 2 it's -1 (no element to its right).Input: arr[] = [2, 3, 1, 9]
Output: [9, 9, 9, -1]
Explanation: For each element except 9 the greatest element on its right is 9.
Table of Content
Use two nested loops. For each element, scan the remaining elements to its right to find the maximum value. Replace the current element with this maximum. Since the very last element has nothing to its right, manually replace it with -1.
17 5 5 5 2 -1
Instead of repeatedly looking ahead to the right for every single element, start from the very end of the array and move left, keep track of the "largest number seen so far."
For each position, replace the current number with "largest seen so far," and then check if the number just replaced is bigger than tracked maximum. If it is, it becomes the new maximum for the elements to its left.
For example, arr[] = [16, 17, 4, 3, 5, 2], max_so_far = -1
- Index 5 (Original = 2): Replace 2 with -1. arr is [16, 17, 4, 3, 5, -1]. New max becomes max(-1, 2) = 2
- Index 4 (Original = 5): Replace 5 with 2. arr is [16, 17, 4, 3, 2, -1]. New max becomes max(2, 5) = 5
- Index 3 (Original = 3): Replace 3 with 5. arr is [16, 17, 4, 5, 2, -1]. New max becomes max(5, 3) = 5
- Index 2 (Original = 4): Replace 4 with 5. arr is [16, 17, 5, 5, 2, -1]. New max becomes max(5, 4) = 5
- Index 1 (Original = 17): Replace 17 with 5. arr is [16, 5, 5, 5, 2, -1]. New max becomes max(5, 17) = 17
- Index 0 (Original = 16): Replace 16 with 17. arr is [17, 5, 5, 5, 2, -1]. New max becomes max(17, 16) = 17
Final Array: [17, 5, 5, 5, 2, -1]
17 5 5 5 2 -1