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.
这道题求进行一次交易能得到的最大利润。如果用brute force的解法就是对每组交易都看一下利润,取其中最大的,总用有n*(n-1)/2个可能交易,所以复杂度是O(n^2)。
跟Maximum Subarray非常类似,用“局部最优和全局最优解法”。思路是维护两个变量,一个是到目前为止最好的交易,另一个是在今天卖出的最佳交易(也就是局部最优。
*maxCur = maximum value sold today
*maxSoFar = maximum value found so far
class Solution { public int maxProfit(int[] prices) { // local[i] = max(local[i-1] + prices[i] - prices[i-1], prices[i] - prices[i-1]) // global[i] = max(global[i-1], local[i] > 0? local[i] : 0) int local = 0, global = 0; for (int i = 1; i < prices.length; i++) { int diff = prices[i] - prices[i-1]; local = Math.max(local + diff, diff); global = Math.max(global, local > 0? local : 0); } return global; } }