天天看點

[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>,周遊整個數組,如果目前元素的值小于買入價格,則将該元素值設為買入價格;如果目前元素值大于等于下一進制素值(該值為極大值),則将局部最大值設為目前元素值與買入價格的內插補點,再将局部最大值與全局最大值進行比較,如果,如果大于全局最大值,則将局部最大值賦給全局最大值。最後得到的全局最大值即為所求。