best time buy and sell stock系列
最近把leetcode上“best time buy and sell stock”系列一共5个问题整理了一下,题目就补贴出来了,在leetcode上面就能找到。
best time buy and sell stock 1
public int maxProfit(int[] prices) {
if (prices==null || prices.length == 0) {
return 0;
}
int maxProfile = 0;
int minValue = 1 << 30;
for(int price:prices) {
minValue = Math.min(minValue,price);
maxProfile = Math.max(maxProfile,price-minValue);
}
return maxProfile;
}
best time buy and sell stock2
public int maxProfit(int[] prices) {
/*if(prices==null || prices.length==0) {
return 0;
}*/
int sum = 0;
int diff;
for(int i=1;i<prices.length;i++){
diff = prices[i] - prices[i-1];
if(diff>0) {
sum+=diff;
}
}
return sum;
}
best time buy and sell stock3
public int maxProfit(int[] prices) {
if(prices==null||prices.length==0){
return 0;
}
int[] left = new int[prices.length];
int[] right = new int[prices.length];
for(int i=1;i<prices.length;i++){
left[i] = left[i-1] + Math.max(prices[i]-prices[i-1],0);
}
for(int i=prices.length-1;i>0;i--){
right[i-1] = right[i] + Math.max(prices[i] - prices[i-1],0);
}
int max = Integer.MIN_VALUE;
for(int i=0;i<prices.length;i++){
if(i<prices.length-1) {
max = Math.max(left[i] + right[i+1],max);
} else {
max = Math.max(max,left[i]);
}
}
return max;
}
best time buy and sell stock 4
public int maxProfit(int k, int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
if (k>=prices.length/2){
int sum = 0;
for(int i=1;i<prices.length;i++){
sum = Math.max(sum,sum + prices[i]-prices[i-1]);
}
return sum;
}
int curMax;
int[] dp = new int[prices.length];
for(int i=1;i<=k;i++){
curMax = 0 - prices[0];
for(int j=1;j<prices.length;j++){
curMax = Math.max(curMax,dp[j]-prices[j]);
dp[j] = Math.max(dp[j-1],curMax+prices[j]);
}
}
return dp[prices.length-1];
}
best time buy and sell stock with cool down
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int[]buy = new int[prices.length];
int[]sell = new int[prices.length];
sell[0] = 0;
buy[0] = 0-prices[0];
int maxProfile = 0;
for(int i=1;i<prices.length;i++){
if(i>1){
buy[i] = Math.max(buy[i-1]+prices[i-1]-prices[i],sell[i-2]-prices[i]);
}else{
buy[i] = buy[i-1]+prices[i-1]-prices[i];
}
sell[i] = Math.max(sell[i-1]-prices[i-1]+prices[i],buy[i-1] + prices[i]);
maxProfile = Math.max(maxProfile,sell[i]);
}
return maxProfile;
}