LeetCode123. Best Time to Buy and Sell Stock III
题目
Say you have an array for which the i i ith element is the price of a given stock on day i i i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
思路
原题目等价于找到两对极小极大值, 使得他们之差的总和最大.
最优解法只需要 O(n) 的复杂度, 逻辑… 有点难讲, 先占坑日后一定会回来填!!
代码 ( C语言, 复杂度 O(n) )
int max(int a, int b) {
return (a > b) ? a : b;
}
int maxProfit(int* prices, int pricesSize){
int before1 = 0x80000000;
int before2 = 0x80000000;
int after1 = 0;
int after2 = 0;
for (int i = 0; i < pricesSize; i++) {
before1 = max(before1, 0-prices[i]);
after1 = max(after1, before1+prices[i]);
before2 = max(before2, after1-prices[i]);
after2 = max(after2, before2+prices[i]);
}
return after2;
}