天天看点

[LeetCode] Best Time to Buy and Sell Stock

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.

首先设定股票买入价格为<code>prices[0]</code>,遍历整个数组,如果当前元素的值小于买入价格,则将该元素值设为买入价格;如果当前元素值大于等于下一元素值(该值为极大值),则将局部最大值设为当前元素值与买入价格的差值,再将局部最大值与全局最大值进行比较,如果,如果大于全局最大值,则将局部最大值赋给全局最大值。最后得到的全局最大值即为所求。