We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Data Structures
- Stacks
- Largest Rectangle
- Discussions
Largest Rectangle
Largest Rectangle
+ 0 comments My c++ code using recursion: T.C -> O(n) S.C -> O(n)
long largestRectangle(vector<int> h) { long maxArea; //base case if (h.empty()) { return 0; } //second stack to divide the current stack in two vector<int> a; //minimum element present in current stack int minimum = *min_element(h.begin(),h.end()); //divide the stack while (h.back()!=minimum) { a.push_back(h.back()); h.pop_back(); } // find area using minimum value stack long ar = minimum * (a.size() + h.size()); //remove the minimum value h.pop_back(); //compare the max area of current stack and that from the divided stack using recursion maxArea = max(ar,max(largestRectangle(a),largestRectangle(h))); return maxArea; }
+ 0 comments JS code :
function largestRectangle(h) { let largest = 0; let n = h.length; for(let i = 0; i < n ; i++){ let counter = 1; for(let j = i - 1; j >= 0 ; j--){ if(j < 0 || h[j] < h[i]){ break; } counter++; } console.log(h[i] + ' : ' + counter); let temp = i + 1; while(h[temp] >= h[i] && i < n){ counter++; temp++; } if(h[i] * counter > largest) largest = h[i] * counter; } return largest; }
+ 0 comments Not the best algorithm, but works anyway!
let area = 0; for(let i = 0; i < h.length; i++){ let height = h[i] let length = 1 let area1 = 0; let area2 = 0; let j = i+1; //forward traversal while(j < h.length){ if(height > h[j])break if(height <= h[j])length++ j++ } area1 = (height*length); j = i-1; length = 1; // Backward Traversal while(j >= 0){ if(height > h[j])break if(height <= h[j])length++ j--; } area2 = (height*(length-1)); if(area < (area1+area2))area = (area1+area2) } return area;
+ 0 comments for each point, count LEFT and RIGHT length, then evaluate AREA = HEIGHT * (LEFT + RIGHT + 1). important to cast long for c# version
public static long largestRectangle(List<int> h) { long max = 0; for(int i=0;i<h.Count;i++) { int n = h[i]; int l = 0; for(int j=i-1;j>=0;j--) { int nl = h[j]; if (nl < n) break; l++; } int r = 0; for(int j=i+1;j<h.Count;j++) { int nr = h[j]; if (nr < n) break; r++; } long a = (long)n*(long)(l+r+1); if (a > max) max = a; } return max; }
+ 0 comments //My C Language Code
long largestRectangle(int h_count, int* h) {
long max=LONG_MIN; int count=0; int mul; for(int i=0;i<h_count;i++){ for(int k=i;k>=0;k--){ if(h[i]<=h[k]){ count++; } else break; } for(int j=i+1;j<h_count;j++){ if(h[i]<=h[j]){ count++; } else break; } mul=h[i]*count; count=0; if(max < mul) max=mul; } return max;
}
Load more conversations
Sort 583 Discussions, By:
Please Login in order to post a comment