1. 只允许一次交易,找差值最大的波峰和波谷。
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;
int profit = 0;
int curPriceMin = Integer.MAX_VALUE;
for (int price : prices) {
profit = Math.max(profit, price - curPriceMin);
curPriceMin = Math.min(curPriceMin, price);
}
return profit;
}
2. 可以进行多次交易,但交易不能重复。找多个波峰波谷。
class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;
int profit = 0;
for (int i = 1; i < prices.length; i++) {
int diff = prices[i] - prices[i - 1];
if (diff > 0) profit += diff;
}
return profit;
}
};
3. 最多可以交易两次,不可以重复交易。先算,前半部分的最大利润再算后半部分的最大利润,最后统计
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;
// get profit in the front of prices
int[] profitFront = new int[prices.length];
profitFront[0] = 0;
for (int i = 1, valley = prices[0]; i < prices.length; i++) {
profitFront[i] = Math.max(profitFront[i - 1], prices[i] - valley);
valley = Math.min(valley, prices[i]);
}
// get profit in the back of prices, (i, n)
int[] profitBack = new int[prices.length];
profitBack[prices.length - 1] = 0;
for (int i = prices.length - 2, peak = prices[prices.length - 1];i >= 0; i--) {
profitBack[i] = Math.max(profitBack[i + 1], peak - prices[i]);
peak = Math.max(peak, prices[i]);
}
// add the profit front and back
int profit = 0;
for (int i = 0; i < prices.length; i++) {
profit = Math.max(profit, profitFront[i] + profitBack[i]);
}
return profit;
}
4. 最多可以交易K次。动态规划。
public int maxProfit(int[] prices) {
public int maxProfit(int k, int[] prices) {
if (prices == null || prices.length <= 1 || k <= 0) return 0;
int n = prices.length;
if (k >= n / 2) {
int profit_max = 0;
for (int i = 1; i < n; i++) {
if (prices[i] - prices[i - 1] > 0) {
profit_max += prices[i] - prices[i - 1];
}
}
return profit_max;
}
int[][] f = new int[n + 1][k + 1];
for (int j = 1; j <= k; j++) {
for (int i = 1; i <= n; i++) {
for (int x = 0; x <= i; x++) {
f[i][j] = Math.max(f[i][j], f[x][j - 1] + profit(prices, x + 1, i));
}
}
}
return f[n][k];
}
private int profit(int[] prices, int l, int u) {
if (l >= u) return 0;
int valley = Integer.MAX_VALUE;
int profit_max = 0;
for (int i = l - 1; i < u; i++) {
profit_max = Math.max(profit_max, prices[i] - valley);
valley = Math.min(valley, prices[i]);
}
return profit_max;
}
};