123. Best Time to Buy and Sell Stock III
来源:互联网 发布:网络流行语mgt什么意思 编辑:程序博客网 时间:2024/05/22 05:10
题目:
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.
只允许交易两次,找出最大利润。
动态规划
定义:int[][] local = new int[length][3]; local[i][j]表示第i天进行j次交易后最优解(必须包含当前天的最优解)。
int[][] global = new int[length][3]; global[i][j]表示表示第i天进行j次交易后最优解。初始状态:local 和global 都为0.
状态转移:
local[i][j]=Math.max(global[i-1][j-1]+Math.max(diff,0),local[i-1][j]+diff);
其中global[i-1][j-1]+Math.max(diff,0)表示前一天少一次交易的最优解,加上今天交易一次的大于0差值、local[i-1][j]+diff表示前一天进行j次交易的最优解加上今天的差值.
global[i][j]=Math.max(local[i][j],global[i-1][j]);
其中local[i][j]表示加上今天差值的最优解,若比global[i-1][j]大则global[i][j]=local[i-1][j],反之同理。
public int maxProfit(int[] prices) { if(prices==null || prices.length==0) return 0; int length=prices.length; int[][] local = new int[length][3]; int[][] global = new int[length][3]; int diff = 0; for(int i=1;i<prices.length;++i) { diff=prices[i]-prices[i-1]; for(int j=1;j<3;++j){// local[i][j]:前一天进行j-1次交易全局变量与前一天进行j次交易的局部最优中找最大值。即选择今天交易或者不交易。 local[i][j]=Math.max(global[i-1][j-1]+Math.max(diff,0),local[i-1][j]+diff); global[i][j]=Math.max(local[i][j],global[i-1][j]); } } return global[length-1][2]; }
阅读全文
0 0
- LeetCode 123. Best Time to Buy and Sell Stock III
- 123.Best Time to Buy and Sell Stock III
- [Leetcode]123.Best Time to Buy and Sell Stock III
- [Leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123.Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [LeetCode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- Leetcode 123. Best Time to Buy and Sell Stock III
- C#实现自动升级(附源码)
- 图像连通域分析(Two-Pass & DFS )
- codeforces 894C
- Aerospike的bin内存管理--即列内存管理
- Linux 静态库使用
- 123. Best Time to Buy and Sell Stock III
- char *s=“hello” 和 char s[]=“hello”的 区别
- 洛谷p1135 奇怪的电梯
- BZOJ3836: [Poi2014]Tourism
- 面试百度新浪头条b站阿里的研发实习生面试记录
- 3
- 输入三个数,并使其从大到小输出
- bzoj2599 [IOI2011]Race
- 机器学习十八:支持向量机(LinearSVM)