-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmaxprofit.go
59 lines (51 loc) · 1.19 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
59
/*
121. Best Time to Buy and Sell Stock
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction
(i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
*/
// time: 2018-12-28
package maxprofit
// dynamic programming
// for every price, find the max profit, then record the current minimum price.
// time complexity: O(n)
// space complexity: O(1)
func maxProfit(prices []int) int {
n := len(prices)
if 0 == n || 1 == n {
return 0
}
var (
res int
minPrice = prices[0]
)
for _, price := range prices {
if price-minPrice > res {
res = price - minPrice
}
if price < minPrice {
minPrice = price
}
}
return res
}
// brute force
// time complexity: O(n^2)
// space complexity: O(1)
func maxProfit1(prices []int) int {
n := len(prices)
if 0 == n || 1 == n {
return 0
}
res := 0
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
if prices[i]-prices[j] > res {
res = prices[i] - prices[j]
}
}
}
return res
}