-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHisto.java
75 lines (58 loc) · 2.1 KB
/
Histo.java
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
68
69
70
71
72
73
74
75
public class histo {
public static int HistogramArea(int[] arr) {
int area = 0;
int maiorArea = 0;
int elemBefore = 0;
if(arr.length == 1)
return arr[0];
for (int i = 0; i < arr.length; i++) {
int elem = arr[i];
if (i == 0) {
area = elem;
maiorArea = area;
} else {
/*
if it's not the first elem, get the previous
to compare
*/
elemBefore = arr[i - 1];
/*
if the current elem is bigger, it means we can either use its area or sum *at least*
the same amout as the previous elem
*/
if (elem >= elemBefore) {
if (elem > area) {
area = elem;
} else {
area += elemBefore;
}
} else {
/*
If it's smaller, check the area behind current elem to see if we have space
to expand the area by the amount of the current elem.
If we find a smaller element, break loop because otherwise we'd have to 'shorten'
the area.
*/
area = 0;
for (int j = i ; j >= 0; j--) {
if (arr[j] >= elem) {
area += elem;
} else {
break;
}
}
}
if (area > maiorArea) {
maiorArea = area;
}
}
}
return maiorArea;
}
public static void main(String[] args) {
// keep this function call here
//Scanner s = new Scanner(System.in);
int[] ar = new int[]{6, 3, 1, 4, 12,4, 5};
System.out.print(HistogramArea(ar));
}
}