03. Maximum Index
The problem can be found at the following link: Question Link
My approach
It creates two vectors
v_min
andv_max
, each of sizen
. These vectors will store the minimum and maximum values encountered so far from the left and right sides of the array, respectively.The first element of
v_min
is initialized asarr[0]
(the first element of the array), and the last element ofv_max
is initialized asarr[n - 1]
(the last element of the array).Two loops are used to populate the
v_min
andv_max
vectors. Starting from the second element (i = 1
), the loop calculates the minimum value between the current element and the previous minimum value and stores it inv_min[i]
. Similarly, starting from the second-to-last element (n - i - 1
), the loop calculates the maximum value between the current element and the next maximum value and stores it inv_max[n - i - 1]
.After populating the
v_min
andv_max
vectors, the code initializesans
(the maximum difference) to 0 and setsi
andj
to 0.A while loop is used to iterate until either
i
orj
reaches the end of the array. The loop checks if the current minimum value (v_min[i]
) is less than or equal to the current maximum value (v_max[j]
). If true, it updates the maximum difference (ans
) if the difference betweenj
andi
is greater than the current maximum difference. Then, it incrementsj
to consider the next element. Otherwise, it incrementsi
to consider the next element.Finally, when the while loop finishes, the function returns the maximum difference (
ans
).
Time and Auxiliary Space Complexity
Time Complexity :
O(n)
as it performs iterations only up ton
.Auxiliary Space Complexity :
O(n)
because we uses two additional arrays,v_min
andv_max
, of the same size ofn
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated