题目链接:https://www.lintcode.com/problem/best-time-to-buy-and-sell-stock-iii/description
const INT_MAX = int(^uint(0) >> 1)
const INT_MIN = ^INT_MAX
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
func maxProfit(prices []int) int {
// write your code here
var n int = len(prices)
if (n == 0) {
return 0;
}
//var dp [n + 1][5 + 1]int
var dp = make([][]int, n + 1);
for i := 0; i < n + 1; i++ {
dp[i] = make([]int, 6);
}
var k int = 1;
for k = 1; k <= 5; k++ {
dp[0][k] = INT_MIN;
}
dp[0][1] = 0;
var i, j int;
for i = 1; i <= n; i++ {
// 手中未持有股票
for j = 1; j <= 5; j += 2 {
// 前一天也未持有
dp[i][j] = dp[i - 1][j];
if (j > 1 && i > 1 && dp[i - 1][j - 1] != INT_MIN) {
// 前一天持有,今天卖了获利。
dp[i][j] = Max(dp[i][j], dp[i - 1][j - 1] + prices[i - 1] - prices[i - 2]);
}
}
// 手中持有股票
for j = 2; j <= 5; j += 2 {
//前一天未持有,今天买进
dp[i][j] = dp[i - 1][j - 1];
if (i > 1 && dp[i - 1][j] != INT_MIN) {
// 前一天持有了,计算今天的利润
dp[i][j] = Max(dp[i][j], dp[i - 1][j] + prices[i - 1] - prices[i - 2]);
}
}
}
var res int = 0;
for j = 1; j <= 5; j += 2 {
res = Max(res, dp[n][j]);
}
return res;
}
func Max(x, y int) int {
if (x > y) {
return x;
}
return y;
}
func main() {
fmt.Println(INT_MAX, " and ", INT_MIN);
var prices1 = []int{4,4,6,1,1,4,2,5};
var profit1 = maxProfit(prices1);
fmt.Println(profit1);
}