-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolution.java
More file actions
84 lines (63 loc) · 1.88 KB
/
Solution.java
File metadata and controls
84 lines (63 loc) · 1.88 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
76
77
78
79
80
81
82
83
84
package hackrank.algorithm.dynamic.maxstock;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Stock Maximize Challenge
*
* @see https://www.hackerrank.com/challenges/stockmax
*/
public class Solution {
public static void main(String[] args) {
for (List<Integer> prices : readInput(System.in)) {
System.out.println(calcMaxProfit(prices));
}
}
public static long calcMaxProfit(List<Integer> prices) {
long cost = 0;
long profit = 0;
long stocks = 0;
int max = -1;
for (int i = 0; i < prices.size(); i++) {
if (max == -1) {
max = findMax(prices, i);
}
int price = prices.get(i);
if (price == max) {
profit += price * stocks;
stocks = 0;
max = -1;
} else {
cost += price;
stocks++;
}
}
return profit - cost;
}
private static int findMax(List<Integer> prices, int start) {
int max = -1;
for (int i = start; i < prices.size(); i++) {
int price = prices.get(i);
if (price > max) {
max = price;
}
}
return max;
}
public static List<List<Integer>> readInput(InputStream stream) {
Scanner scanner = new Scanner(stream);
int testCases = scanner.nextInt();
List<List<Integer>> data = new ArrayList<>(testCases);
for (int t = 0; t < testCases; t++) {
int size = scanner.nextInt();
List<Integer> prices = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
prices.add(scanner.nextInt());
}
data.add(prices);
}
scanner.close();
return data;
}
}