您的位置:首页 > 其它

123 Best Time to Buy and Sell Stock III

2016-02-03 16:20 309 查看
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

题目:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


解题思路:

这题的考点是动态规划

这题是 188 Best Time to Buy and Sell Stock IV 这题的特殊情况。即 k = 2 时。

代码实现:

public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;
int[] local = new int[3];
int[] global = new int[3];
for(int i = 1; i < prices.length; i ++) {
int diff = prices[i] - prices[i - 1];
for(int j = 2; j >= 1; j --) {
local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff);
global[j] = Math.max(global[j], local[j]);
}
}
return global[2];
}
}


198 / 198 test cases passed.
Status: Accepted
Runtime: 9 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: