您的位置:首页 > 编程语言 > Java开发

[Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III

2015-01-06 22:28 435 查看
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天卖出所能得到的最大利润。不断更新这个利润,最后得到的即为最大利润值。

public int maxProfit(int[] prices) {
if(prices.length<=0)
return 0;
int buy = prices[0];
int benifit = 0;
for(int i=0;i<prices.length;i++) {
benifit = Math.max(benifit, prices[i]-buy);
buy = Math.min(buy, prices[i]);
}
return benifit;
}


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).

无限次买卖股票,看似更难,实际更简单了。只需要得到所有攀升段的总值,即为总最大利润。那么只要第二天值比第一天更贵,则把它们的差值加到总利润。

public int maxProfit(int[] prices) {
int re = 0;
for(int i=1;i<prices.length;i++) {
if(prices[i]>prices[i-1])
re += prices[i]-prices[i-1];
}
return re;
}


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; 如果只有一天也将无利润

public int maxProfit(int[] prices) {
if(prices.length<=1)
return 0;
int k=2;
int[][] dp = new int[k+1][prices.length];
int re = 0;
for(int i=1;i<=k;i++) {
int temp = dp[i-1][0]-prices[0];
for(int j=1;j<prices.length;j++) {
temp = Math.max(temp, dp[i-1][j]-prices[j]);
dp[i][j] = Math.max(dp[i][j-1], prices[j]+temp);
}
}
return dp[k][prices.length-1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: