-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem121.swift
42 lines (37 loc) · 1.07 KB
/
problem121.swift
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
class Solution1 {
func maxProfit(_ prices: [Int]) -> Int {
var min = Int.max; var profit = 0
for price in prices {
if (price < min) {
min = price
} else {
profit = max(profit, price - min)
}
}
return profit
}
}
//sorting the price together with date
class Solution2 {
func maxProfit(_ prices: [Int]) -> Int {
let length = prices.count
let prices = prices.enumerated().sorted{$0.element < $1.element}
var res = 0; var prev = Int.max
for i in 0..<length {
var j = length - 1
if (prices[i].offset > prev) {
prev = prices[i].offset
continue
}
prev = prices[i].offset
while (j > i) {
if (prev < prices[j].offset) {
res = max(prices[j].element - prices[i].element, res)
break
}
j -= 1
}
}
return res
}
}