Given N non-negative integers a1,a2,….an where each represents a point at coordinate (i, ai). N vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i,0). Find two lines, which together with x-axis forms a container, such that it contains the most water.
Time : O(n)
Space : O(1)
1 2 3 4 5 6 7 8 9 10
longlongmaxArea(longlong A[], int len) { longlong res = 0, l = 0, r = len - 1; while(l < r) { res = max(res, (r - l) * (min(A[r], A[l]))); if(A[l] < A[r]) l++; else r--; } return res; }
Time : O(n)
Space : O(1)
range of A[i] is [0 ... 100] so space is biggest stack size is 100 witch is constant O(1)
also, stack is constant, time complexity became O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
longlongmaxArea(longlong A[], int len) { vector<int> st; longlong res = 0; for(int i = 0; i < len; i++) { for(int j = 0; j < st.size(); j++) { longlong h = min(A[i], A[st[j]]), w = i - st[j]; res = max(res, h * w); }
if(st.empty() or A[st.back()] < A[i]) st.push_back(i); } return res; }