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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
1 2 3 4 5 6 7 8 9 10 |
func maxProfit(_ prices: [Int]) -> Int { if prices.count < 2 { return 0 } var p = prices[0], m = 0 for i in 1..<prices.count { m = max(m, prices[i] - p) p = min(p, prices[i]) } return m } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼