[ LeetCode ] 121, 122 Best Time to Buy and Sell Stock
121. 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. 思路: O(n) 定義買點為目前最小值 並找出目前最大好處 buy = min( buy, i ) res = max( res, i - buy) 122. Best Time to Buy and Sell Stock II ou may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 思路: O(n) 只要明天比今天的價更高 就值得投資. 掃一遍 prices 如果 prices[i+1]大於今天的值 累加...