描述
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.
分析
要理解题意,给定一只股票一段时间内每天的估价,做一下事后诸葛亮,问如果只做一次交易(买一次买一次,注意不能卖空,所以必须先买后卖),所以就是找到低价,然后高价卖出,要求是低价必须在高价前面。扫描一遍数组即可,维护当前的最大利润和当前最低价。
代码
Python
1 | class Solution(object): |