首页 > 代码库 > Best Time to Buy and Sell Stock I II III
Best Time to Buy and Sell Stock I II III
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.
创建差分数组,即差分数组grid[i] = price[i+1]-price[i],因此,本题可以转化为求grid中最大子数组和问题
1 public int maxProfit(int[] prices) { 2 if(prices.length<=1){ 3 return 0; 4 } 5 int minus[] = new int[prices.length-1]; 6 for(int i=0;i<minus.length;i++){ 7 minus[i] = prices[i+1]-prices[i]; 8 } 9 int max = minus[0]; 10 int now = minus[0]; 11 for(int i=1;i<minus.length;i++){ 12 if(minus[i]+now <minus[i]){ 13 now = minus[i]; 14 }else{ 15 now = minus[i]+now; 16 } 17 if(max<now){ 18 max = now; 19 } 20 } 21 return max>0?max:0; 22 }
Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You 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).
还是差分数组,把数组中所有正数加起来就是了。。。
1 public int maxProfit(int[] prices) { 2 if(prices.length<=1){ 3 return 0; 4 } 5 int max = 0; 6 for(int i=0;i<prices.length-1;i++){ 7 int minus = prices[i+1]-prices[i]; 8 max+=minus>0?minus:0; 9 } 10 return max; 11 }
Best Time to Buy and Sell Stock III
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
动态规划,用两个数组记录状态,f[i]表示区间[0,i](0<=i<=n-1) 的最大利润,g[i]表示区间[i,n-1](0<=i<=n-1) 的最大利润。
1 public int maxProfit(int[] prices) { 2 if (prices.length < 2) 3 return 0; 4 int f[] = new int[prices.length]; 5 int g[] = new int[prices.length]; 6 for (int i = 1, valley = prices[0]; i < prices.length; ++i) { 7 valley = Math.min(valley, prices[i]); 8 f[i] = Math.max(f[i - 1], prices[i] - valley); 9 } 10 for (int i = prices.length - 2, peak = prices[prices.length - 1]; i >= 0; --i) { 11 peak = Math.max(peak, prices[i]); 12 g[i] = Math.max(g[i], peak - prices[i]); 13 } 14 int max_profit = 0; 15 for (int i = 0; i < prices.length; ++i) 16 max_profit = Math.max(max_profit, f[i] + g[i]); 17 return max_profit; 18 }