LC121:最多只允许完成一笔交易
dp[i]表示前i天所能获得的最大利润
public int maxProfit(int[] prices) {
int len = prices.length;
if (len <= 1) {
return 0;
}
int[] dp = new int[len];
dp[0] = 0;
int minPrice = prices[0];
for (int i = 1; i < len; i++) {
if (minPrice > prices[i]) {
minPrice = prices[i];
}
dp[i] = Math.max(prices[i] - minPrice, dp[i - 1]);
}
return dp[len - 1];
}
LC122:可以多次交易买卖
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
int tmp = prices[i] - prices[i - 1];
if (tmp > 0) profit += tmp;
}
return profit;
}