#include <iostream>
int main() {
int N = 0, harvested_water = 0;
std::cin >> N;
int *arr = new int[N];
for (int i = 0; i < N; ++i) std::cin >> arr[i];
for (int i = 0; i < N; ++i) {
int left_max = 0, right_max = 0;
for (int j = i; j >= 0; --j)
if (arr[j] > left_max) left_max = arr[j];
for (int j = i; j < N; ++j)
if (arr[j] > right_max) right_max = arr[j];
int min_bound = (left_max < right_max) ? left_max : right_max;
harvested_water += min_bound - arr[i];
}
std::cout << harvested_water;
}
Getting TLE in 3 test cases, please help also tell me why?
Two nested for loops is causing your time complexity in o(N^2) for worst cases and all the three cases in which you are getting TLE are designed for worst case only. Solve this in o(N) time.
Hint make 2 different arrays and store left max for ith index in one array and store right max for ith index in second array. If you want any help with coding implementation, you can ask me i will help you with that as you are trying this problem from tomorrow and both of your doubts are with me. Reply here only if you want any assistance regarding this problem.
Thanks for the help, although I can do it myself with the two more arrays, I just though that it would increase space complexity so I was trying it this way. Well, let me give that a try. Also I got to know one more thing, that is time complexity is more important over space complexity.
General trend. In your course you will hear this from prateek bhaiya too (if he is in your coourse video lectures) with an example that if you are using amazon site then you will need faster experience for product searches whereas the apk memory won’t bother you, but lag will. This question can be solved by using stack too but that implementation is relatively slow as of array implementation . Now you can proceed accordingly.
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.