The optimize approach given in the editorial


if array={3 0 0 2 0 4 } n=6 as in program
we use two pointer approach
left pointer=0 and right pointer =n-1
(arr[lo] < arr[hi]) this condition never false how it is switch to else condition in the loop in line no 37 that were i am confused

hey @dipeshgupta197 take your own test case. Like in this one itself you can take {3,0,0,2,0,2} you will get the output as 6 which is correct output.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

sir maine two approach se kiya phele program first simple approach to go the every element of the array check the water saved
next approach is using precomputed left max and right max array
the third approach I saw but didn’t understand as I feel ki line no 37 prr code kabhi switch bhi karega agar array vo hein jo maine aapko likhkar bhejii (3 0 0 2 0 4) because output tooo 10 aaraha hein jo sahi hein but when I dry run on copy I didn’t get it so pls get my query

while (lo <= hi)

{

    if (arr[lo] < arr[hi])

    {

        if (arr[lo] > left_max)

        {

            left_max = arr[lo]; // Updating left_max

        }

        else

        {

            water += left_max - arr[lo]; // Calculating the ans

        }

        lo++;

    }

    else

    {

        if (arr[hi] > right_max)

        {

            right_max = arr[hi]; // Updating right_max

        }

        else

        {

            water += right_max - arr[hi]; // Calculating the ans

        }

        hi--;

    }

}

cout<<water<<endl;

return 0;

}
see sir my array is {3 0 0 2 0 4} lo=starts from 0 and hi starts from n-1 loop is running till lo is<=hi in this case li=0 and hi=5 then if(arr[lo]<arr[hi) this condition never fails because arr[lo]
is always less than arr[hi] this is my doubt array hii khatam hoojaegi

now i got the way sir understand the code either we use left max or right max to get saved water depends upon arr[lo] arr[hi] which ever is smaller and then do two either update my left max or water and right max or water

@dipeshgupta197 yes it depends on the given values you either update you left or right answer or you add sum value to your final answer.

1 Like