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.
因为只能交易一次,动态规划,不停寻找中···
利润=卖出的高价-收入的低价
把一段时间内的最低价得到,用其之后的价格-低价,求出最大利润
如果有更低的价格出现,更变低价,求得利润,继续和之前的最大利润比较。
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2)
return 0;
//最大利润
int maxprofit=0;
//最低价格,初始为第一天的价格
int minprice=prices[0];
for(int i=1;i<prices.length;i++){
//比较得到当前的最低价格
minprice=Math.min(minprice,prices[i]);
//计算利润,求出当前的最大利润
maxprofit=Math.max(maxprofit,prices[i]-minprice);
}
return maxprofit;
}
}
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 class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2) return 0;
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
int diff = prices[i] - prices[i - 1];
if (diff > 0) {
maxProfit += diff;
}
}
return maxProfit;
}
}
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.
开始想不出有什么好的办法,后来看到了别人的解法,茅塞顿开
因为2次交易,所以我们可以找出第i天前交易一次的最大利润,和第i天后的交易的最大利润!
于是就是正着寻找一遍找出了第i天前交易的最大利润
反着来再来一遍找到第i天后的交易的最大利润
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2)
return 0;
int maxProfit=0;
int n = prices.length;
int[] preProfit = new int[n];
int[] postProfit = new int[n];
int curMin = prices[0];
int curMax = prices[n - 1];
for(int i = 1; i < prices.length; i++) {
//找到了第i天前的最大利润
curMin=Math.min(curMin,prices[i]);
preProfit[i]=Math.max(preProfit[i-1],prices[i]-curMin);
//第i天后的最大利润
curMax=Math.max(curMax,prices[n-i-1]);
postProfit[n-1-i]=Math.max(postProfit[n-i],curMax-prices[n-1-i]);
}
for(int i=0;i<prices.length;i++){
//求和,求出最大值
maxProfit=Math.max(maxProfit,preProfit[i]+postProfit[i]);
}
return maxProfit;
}
}