题目
方法一:动态规划
public class MaxProfit2 {
public int maxProfit(int[] prices) {
//动态规划
//每天都有持有和不持有之分,设dp[i][0]持有的利润,dp[i][1]不持有的利润。
//持有分两种情况 1、前天持有今天不操作即 dp[i-1][0]。2、前天不持有今天买入即(可以多次交易,之前可能会存在交易,故前天不持有可能会有利润)dp[i-1][1] - prices[i]。
//dp[i][0] = max(dp[i-1][0], - prices[i])
//不持有分两种情况 1、前天不持有今天不操作即 dp[i-1][1]。2、前天持有今天卖出即 dp[i-1][0] + prices[i]。
//dp[i][1] = max(dp[i-1][1], (dp[i-1][0] + prices[i]))
int len = prices.length;
if (len < 2) {
return 0;
}
int dp[] = new int[2];
dp[0] = -prices[0];
dp[1] = 0;
//System.out.println(dp[0][0]+" "+dp[0][1]);
for (int i = 1; i < len; i++) {
dp[0] = Math.max(dp[0], dp[1]-prices[i]);
dp[1] = Math.max(dp[1], dp[0]+prices[i]);
System.out.println(dp[0]+" "+dp[1]);
}
return dp[1];
}
public static void main(String[] args) {
MaxProfit2 maxProfit = new MaxProfit2();
int[] prices = {7,1,5,3,6,4};
//int[] prices = {7,6,4,3,1};
System.out.println(maxProfit.maxProfit(prices));
}
}
LeetCode测试结果
方法二:贪心
public class MaxProfit2 {
public static void main(String[] args) {
MaxProfit2 maxProfit = new MaxProfit2();
//int[] prices = {7,1,5,3,6,4};
//int[] prices = {7,6,4,3,1};
int[] prices = {1,2,3,4,5};
System.out.println(maxProfit.maxProfit(prices));
}
public int maxProfit(int[] prices) {
//贪心 有利润买卖
int len = prices.length;
int max = 0;
for (int i = 1; i < len; i++) {
if (prices[i] > prices[i-1]) {
max += prices[i] - prices[i-1];
}
}
return max;
}
}
LeetCode测试结果