题目
方法一:动态规划
public class MaxProfit {
public int maxProfit(int[] prices) {
//动态规划
//每天都有持有和不持有之分,设dp[i][0]持有的利润,dp[i][1]不持有的利润。
//持有分两种情况 1、前天持有今天不操作即 dp[i-1][0]。2、前天不持有今天买入即(只能交易一次,之前不会存在交易,故前天不持有不会有利润)-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[len][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
//System.out.println(dp[0][0]+" "+dp[0][1]);
for (int i = 1; i < len; i++) {
dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0]+prices[i]);
System.out.println(dp[i][0]+" "+dp[i][1]);
}
return dp[len-1][1];
}
public static void main(String[] args) {
MaxProfit maxProfit = new MaxProfit();
int[] prices = {7,1,5,3,6,4};
System.out.println(maxProfit.maxProfit(prices));
}
}
LeetCode测试结果
方法二:滑动窗口
public class MaxProfit {
public static void main(String[] args) {
MaxProfit maxProfit = new MaxProfit();
//int[] prices = {7,1,5,3,6,4};
int[] prices = {7,6,4,3,1};
System.out.println(maxProfit.maxProfit(prices));
}
public int maxProfit(int[] prices) {
//滑动窗口
//利润最大即 最低买入,最高卖出。
//定义买入的最低值,定义卖出时获取的最大利润。
int len = prices.length;
if (len < 2) {
return 0;
}
int min = Integer.MAX_VALUE;
int max = 0;
for (int i = 0; i < len; i++) {
if (min > prices[i]) {
min = prices[i];
} else if(min < prices[i] && max < prices[i] - min) {
max = prices[i] - min;
}
}
return max;
}
}