-
Notifications
You must be signed in to change notification settings - Fork 0
/
121. Best Time to Buy and Sell Stock
70 lines (62 loc) · 1.99 KB
/
121. Best Time to Buy and Sell Stock
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
class Solution {
public int maxProfit(int[] prices) {
int maxDifference = 0;
int minPrice = 999999;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
maxDifference = Math.max(prices[i] - minPrice, maxDifference);
}
}
return maxDifference;
}
}
class Solution {
static class Price {
int value;
int date;
public Price(int value, int date) {
this.value = value;
this.date = date;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Price price = (Price) o;
return value == price.value &&
date == price.date;
}
@Override
public int hashCode() {
return Objects.hash(value, date);
}
}
public int maxProfit(int[] prices) {
Price[] pricesAndDates = new Price[prices.length];
boolean decreasingSeq = true;
int decreasingSeqEndIdx = 0;
for (int i = 0; i < prices.length; i++) {
if (decreasingSeq && i > 0) {
if (prices[i] > prices[i - 1]) {
decreasingSeq = false;
decreasingSeqEndIdx = i - 1;
}
}
pricesAndDates[i] = new Price(prices[i], i);
}
int maxDifference = 0;
for (int i = decreasingSeqEndIdx; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
if (pricesAndDates[j].date > pricesAndDates[i].date) {
int diff = pricesAndDates[j].value - pricesAndDates[i].value;
if (diff > maxDifference) {
maxDifference = diff;
}
}
}
}
return maxDifference;
}
}