原题链接在这里:https://leetcode.com/problems/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.
题解:
与Maximum Subarray相似,都是全局最优与局部最优问题。
找到一段subarray, 找出最大profit. 如果profit已经小于0了, reset as 0.
local = Math.max(local + diff, 0). 0表示i天股价没有i-1天高. 只可以进行一次交易.
global = Math.max(local, global).
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 //采用局部最优和全局最优 4 if(prices == null || prices.length <= 1){ 5 return 0; 6 } 7 int local = 0; 8 int global = 0; 9 for(int i = 1; i<prices.length; i++){ 10 local = Math.max(local+prices[i]-prices[i-1],0); 11 global = Math.max(local,global); 12 } 13 return global; 14 } 15 }
跟上Best Time to Buy and Sell Stock II, Best Time to Buy and Sell Stock III, Best Time to Buy and Sell Stock IV, Best Time to Buy and Sell Stock with Cooldown, Best Time to Buy and Sell Stock with Transaction Fee.