-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxAreaOfHistogram.java
More file actions
67 lines (58 loc) · 2.47 KB
/
maxAreaOfHistogram.java
File metadata and controls
67 lines (58 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef {
public static void main (String[] args) throws java.lang.Exception {
// Input
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // Number of bars
int[] arr = new int[n]; // Heights of bars
// Reading the heights of the bars
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Arrays to store the next smaller right and next smaller left
int[] nsr = new int[arr.length]; // Next smaller right
int[] nsl = new int[arr.length]; // Next smaller left
Stack<Integer> st = new Stack<>();
// 1. Calculate NSR (Next Smaller Right) array
for (int i = arr.length - 1; i >= 0; i--) {
// Pop elements from the stack until we find a smaller element
while (!st.isEmpty() && arr[st.peek()] >= arr[i]) {
st.pop();
}
// If stack is empty, there is no smaller element to the right
if (st.isEmpty()) {
nsr[i] = arr.length; // Store length of array
} else {
nsr[i] = st.peek(); // Store index of next smaller element
}
st.push(i); // Push current index to the stack
}
// Clear the stack before using it again
st.clear();
// 2. Calculate NSL (Next Smaller Left) array
for (int i = 0; i < arr.length; i++) {
// Pop elements from the stack until we find a smaller element
while (!st.isEmpty() && arr[st.peek()] >= arr[i]) {
st.pop();
}
// If stack is empty, there is no smaller element to the left
if (st.isEmpty()) {
nsl[i] = -1; // No smaller element to the left
} else {
nsl[i] = st.peek(); // Store index of next smaller element
}
st.push(i); // Push current index to the stack
}
// 3. Calculate the maximum area using the NSR and NSL arrays
int maxArea = 0;
for (int i = 0; i < arr.length; i++) {
int width = nsr[i] - nsl[i] - 1; // Calculate the width
int area = arr[i] * width; // Calculate the area
maxArea = Math.max(maxArea, area); // Track the maximum area
}
// Output the maximum area
System.out.println(maxArea);
}
}