题目描述
Say you have an array prices for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are ngaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1] Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路
根据上一题, 我们可以很简单的解决这个题目, 最开始的时候本人陷入了一个常规的题解思路, 假如 数列是 [4,5,6,1,2,3] 这样的, 我在想要判断是否到了峰值, 然后从峰值(6/3)减去谷值(4/1)得到利润(太过于现实化). 其实我们可以简单的使用做题的思路: 如果第N天比第N-1天贵,我们就第N天卖掉,得到一份利润, 然后再用第N天的价格买回来,等待后边某一天卖掉(现实中没人会这么操作.....), 这么一来,题目就变得无比简单
示例代码
func maxProfit(_ prices: [Int]) -> Int {
if prices.count == 0 {
return 0
}
var result = 0
var min = prices.first!
for i in 1..<prices.count {
let temp = prices[i]
if min > temp {
min = temp
}else if (temp - min > 0){
result += prices[i] - min
min = prices[i]
}
}
return result
}
在将代码简化以后, 会更加简洁
func maxProfit(_ prices: [Int]) -> Int {
if prices.isEmpty || prices.count == 1 {
return 0
}
var res = 0
for i in 1..<prices.count {
res += (prices[i] > prices[i-1] ? prices[i]-prices[i-1]: 0)
}
return res
}