买卖股票的最佳时机 III,LeetCode123题
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
//暴力解法,直接遍历,超时
public static int maxProfit0(int[] prices) {
int result = 0;
int length = prices.length;
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) {
int p1 = prices[j] - prices[i];
if (p1 > result) {
result = p1;
}
for (int k = j + 1; k < length; k++) {
for (int l = k + 1; l < length; l++) {
int p2 = prices[l] - prices[k];
if (p2 + p1 > result) {
result = p1 + p2;
}
}
}
}
}
return result;
}
//波峰波谷遍历,超时
public static int maxProfit1(int[] prices) {
int result = 0;
int length = prices.length;
if (length <= 1) {
return 0;
}
List<Integer> troughIndex = new ArrayList<>();
List<Integer> crestIndex = new ArrayList<>();
boolean isClimbing = prices[1] < prices[0];
for (int i = 0; i < length - 1; i++) {
if (isClimbing && prices[i + 1] < prices[i]) {
crestIndex.add(i);
isClimbing = false;
} else if (!isClimbing && prices[i + 1] > prices[i]) {
troughIndex.add(i);
isClimbing = true;
}
}
crestIndex.add(length - 1);
Integer[] trIn = new Integer[troughIndex.size()];
Integer[] crIn = new Integer[crestIndex.size()];
troughIndex.toArray(trIn);
crestIndex.toArray(crIn);
for (int i = 0; i < trIn.length; i++) {
for (int j = i; j < crIn.length; j++) {
if (crIn[j] < trIn[i]) {
continue;
}
int p1 = prices[crIn[j]] - prices[trIn[i]];
if (p1 > result) {
result = p1;
}
for (int k = i + 1; k < trIn.length; k++) {
if (trIn[k] < crIn[j]) {
continue;
}
for (int l = j + 1; l < crIn.length; l++) {
if (crIn[l] < trIn[k]) {
continue;
}
int p2 = prices[crIn[l]] - prices[trIn[k]];
if (p1 + p2 > result) {
result = p1 + p2;
}
}
}
}
}
return result;
}
//正确解法:使用两个辅助数组,计算储存第0到i位最大利润和第i到length位最大利润
public static int maxProfit(int[] prices) {
int result = 0;
int length = prices.length;
int lmin = Integer.MAX_VALUE, lp = 0;
int rmax = 0, rp = 0;
int[] left = new int[length];
int[] right = new int[length];
for (int i = 0; i < length; i++) {
if (prices[i] < lmin) {
lmin = prices[i];
} else if (prices[i] - lmin > lp) {
lp = prices[i] - lmin;
}
if (prices[length - i - 1] > rmax) {
rmax = prices[length - i - 1];
} else if (rmax - prices[length - i - 1] > rp) {
rp = rmax - prices[length - i - 1];
}
left[i] = lp;
right[length - i - 1] = rp;
}
System.out.println(Arrays.toString(left));
System.out.println(Arrays.toString(right));
for (int i = 0; i < length; i++) {
int p = left[i] + right[i];
if (p > result) {
result = p;
}
}
return result;
}