LeetCode刷题实战188:买卖股票的最佳时机 IV
共 1041字,需浏览 3分钟
·
2021-02-19 14:39
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Notice that you may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
题意
示例
示例 1:
输入:k = 2, prices = [2,4,1]
输出:2
解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
示例 2:
输入:k = 2, prices = [3,2,6,5,0,3]
输出:7
解释:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
提示:
0 <= k <= 100
0 <= prices.length <= 1000
0 <= prices[i] <= 1000
解题
class Solution {
public int quick(int[] prices){
int max=0;
for(int i=0;i-1;i++){
if(prices[i+1]>prices[i])
max+=(prices[i+1]-prices[i]);
}
return max;
}
public int maxProfit(int k, int[] prices) {
int len=prices.length;
if(len==1||len==0||prices==null||k==0){
return 0;
}
if(k>=len/2){
return quick(prices);
}
int []buy=new int[k+1];
int []sell=new int[k+1];
for(int i=0;i<=k;i++){
buy[i]=Integer.MIN_VALUE;
}
for(int i=0;ifor (int j = 0; j buy[j+1] = Math.max(buy[j+1], sell[j] - prices[i]);
sell[j+1] = Math.max(buy[j+1] + prices[i], sell[j+1]);
}
}
return sell[k];
}
}