题目描述
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.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路1: 暴力破解
这个题目要求我们只可以买卖一次股票, 首先我们可以用暴力破解法, 使用双重循环, 获取以当前i天的价格, 以后第j天卖股票价格最高, 得到最终结果
时间复杂度: O(n^2)
示例代码1
func maxProfit(_ prices: [Int]) -> Int {
var result = 0
for i in 0..<prices.count {
let left = prices[i]
for j in (i+1)..<prices.count {
let right = prices[j]
if right > left && (right - left) > result {
result = right - left
}
}
}
return result
}
解题思路2: 找最低价
我们优化一下这个解法, 其实可以只用一次循环就可以. 假设第一天的价格是我们买入时的最低价格min, 进行遍历, 如果第i天的价格小于最低价格min, 我们就将第i天的价格设置为min, 如果大于, 我们就计算差价, 并且与之前记录的差价对比, 得到最大差价
时间复杂度: O(n)
示例代码2:
func maxProfit(_ prices: [Int]) -> Int {
var result = 0
var min = Int.max
for i in 0..<prices.count {
if min > prices[i] {
min = prices[i]
}else if (prices[i] - min > result){
result = prices[i] - min
}
}
return result
}