-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxProfit.go
58 lines (49 loc) · 1.31 KB
/
maxProfit.go
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
/*
Use: find the max profit to buy and sell in a given array of prices
Input: array of prices
Output: max profit
*/
func maxProfit(prices []int) int {
maxProfit := 0
if prices == nil {
return maxProfit
} else {
valleyP := 0
for i := 1; i < len(prices); i++ {
peakP := i
// Update the valley if there is a lower valley
if prices[valleyP] > prices[peakP] {
valleyP = peakP
}
// Update the max profit
if maxProfit < prices[peakP] - prices[valleyP] {
maxProfit = prices[peakP] - prices[valleyP]
}
}
}
return maxProfit
}
// Second time solving
/*
Use: find the max profit to buy and sell in a given array of prices
Input: array of prices
Output: max profit
*/
func maxProfit(prices []int) int {
left := 0
right := 1
maxProfit := 0
for i := 1; i < len(prices); i++ {
// jump left to right if right is smallest then him
if prices[right] < prices[left] {
left = right
}
// update maxProfit if current profit is bigger
if prices[right] - prices[left] > maxProfit {
maxProfit = prices[right] - prices[left]
}
// update right
right = i + 1
}
return maxProfit
}