forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStockSpanProblem.java
More file actions
75 lines (65 loc) · 2.22 KB
/
StockSpanProblem.java
File metadata and controls
75 lines (65 loc) · 2.22 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
68
69
70
71
72
73
74
75
package com.geeksforgeeks.stack;
import com.geeksforgeeks.array.ArrayRotation;
import java.util.Stack;
public class StockSpanProblem {
public static void main(String[] args) {
int price[] = {100, 80, 60, 70, 60, 75, 85};
int[] result = new int[price.length];
initializeResult(result);
System.out.println("Calculating Span for " + price.length + " days");
calculateSpanBruteForce(price, price.length, result);
ArrayRotation.printArray(result);
initializeResult(result);
System.out.println("Calculating Span in optimized manner for " + price.length + " days");
calculateSpanOptimized(price, price.length, result);
ArrayRotation.printArray(result);
}
private static void initializeResult(int[] result) {
// For Each Stock Price have at-least 1 stock Span
for (int i = 0; i < result.length; i++) {
result[i] = 1;
}
}
private static void calculateSpanBruteForce(int[] price, int length, int[] result) {
for (int i = length - 1; i > 0; i--) {
for (int j = i - 1; j >= 0; j--) {
if (price[i] > price[j]) {
result[i] += 1;
}
}
}
}
/**
* 1) Push 1st Price into the Stack
* 2) Span_Till_Now = 1
* 3) for i = 0 to length
if(arr[i] < top(stack))
push(arr[i]) into Stack
else
while(peek[stack] < arr[i]) {
spanTillNow += 1
}
push(arr[i]) into Stack
*
* @param price
* @param length
* @param result
*/
private static void calculateSpanOptimized(int[] price, int length, int[] result) {
Stack<Integer> stack = new Stack<>();
stack.push(price[0]);
int MAX_STOCK_SPAN = 1;
for (int i = 1; i < length; i++) {
if (price[i] < stack.peek()) {
stack.push(price[i]);
} else {
while (stack.peek() < price[i]) {
MAX_STOCK_SPAN += 1;
stack.pop();
}
stack.push(price[i]);
result[i] = MAX_STOCK_SPAN;
}
}
}
}