题目摘要
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
解法
从头开始遍历,找最小价格和最大利润:如果某天价格比最小价格小,则设为最小价格,否则和最大利润比较,如果比最大利润大,则设为最大利润。
注意
注意是找最小价格和最大利润两个值,如果找最大价格,可能是负利润而不是正利润(最大价格出现在最小价格之前)
原题
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 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
In this case, no transaction is done, i.e. max profit = 0.