[思路]LeetCode Problems-121. Best Time to Buy and Sell Stock
此篇文章要探討的問題Best Time to Buy and Sell Stock,意指如何在股市波段中找出最大的利潤.題目原文如下: Say you have an array for which the i th 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. 在這題中假設只能買賣一次,你必須在這一次買賣中就獲得最大的利潤.對我們來說這是很簡單從肉眼即可判斷出解答為何(意即:投資者常在看的"K線圖"),那麼對電腦來說,這應該要如何解決? 首先要思考的是:我們自己是 如何判別怎樣算賺錢呢? 對投資者來說,股票賺錢的本質就只是低買高賣,所以重要的往往不是單一的價格本身,而是兩個價格之間的差為多少? 因此,以題目的範例來說,我們感興趣的不是陣列中[7,1,5,3,6,4]的每個值,而是前後兩兩之間的 差 : [ (1-7) , (5-1) , (3-5) , (6-3) , (4-6) ] = [ -6 , 4 , -2 , 3 , -2 ] 接者就可以再進一步判斷, 要從哪一個數開始作連續相加,並要停在哪一個數值上呢? 例如假設是要從-6開始加到4,-2,3的值,還是要從4開始連續加到-2,3的值? 處理序列的...