首页 > 代码库 > [Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III
[Leetcode][JAVA] 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.
买卖股票,只能买卖一次。那么只需要简单遍历一遍,记录利润值和买入值,每次遇到更大的利润值就更新,遇到更小的买入值就更新。这样在每个day i处计算出的利润值为在第i天卖出所能得到的最大利润。不断更新这个利润,最后得到的即为最大利润值。
1 public int maxProfit(int[] prices) { 2 if(prices.length<=0) 3 return 0; 4 int buy = prices[0]; 5 int benifit = 0; 6 for(int i=0;i<prices.length;i++) { 7 benifit = Math.max(benifit, prices[i]-buy); 8 buy = Math.min(buy, prices[i]); 9 }10 return benifit;11 }
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 int re = 0;3 for(int i=1;i<prices.length;i++) {4 if(prices[i]>prices[i-1])5 re += prices[i]-prices[i-1];6 }7 return re;8 }
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).
discussion里有人提出了一个dp方法适用于k次买卖的情况,很好理解。这里就直接照搬他的思路了:
// f[k, ii] 表示直到 prices[ii] 的最大利润 在最多k次交易的情况下.
// 转移函数:f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] } = max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj]))
// 基本情况:f[0, ii] = 0; 0次交易将无利润
// 基本情况:f[k, 0] = 0; 如果只有一天也将无利润
1 public int maxProfit(int[] prices) { 2 if(prices.length<=1) 3 return 0; 4 int k=2; 5 int[][] dp = new int[k+1][prices.length]; 6 int re = 0; 7 for(int i=1;i<=k;i++) { 8 int temp = dp[i-1][0]-prices[0]; 9 for(int j=1;j<prices.length;j++) {10 temp = Math.max(temp, dp[i-1][j]-prices[j]);11 dp[i][j] = Math.max(dp[i][j-1], prices[j]+temp);12 }13 }14 return dp[k][prices.length-1];15 }
[Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III