LeetCode Best Time to Buy and Sell Stock III(dp)
2016-01-23 21:40
441 查看
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).
题意:给出一个数组,数组元素表示股票在第i天的股价,最多只能交易两次,求最大收益
思路:动态规划。用dp1(i)表示从0到i的最小股票值。dp2(i)表示从i到n的最大股票值。在求最大收益值时,将第一次收益的最大值加上第二次收益的最大值相加即可。
代码如下:
class Solution
{
public int maxProfit(int[] prices)
{
int len = prices.length;
if (0 == len) return 0;
int[] left = new int[len];
int[] right = new int[len];
left[0] = prices[0];
right[len - 1] = prices[len - 1];
for (int i = 1; i < len; i++)
{
left[i] = Math.min(left[i - 1], prices[i]);
}
for (int i = len - 2; i >= 0; i--)
{
right[i] = Math.max(right[i + 1], prices[i]);
}
int ans = 0;
int tmp = 0;
for (int i = 0; i < len; i++)
{
tmp = Math.max(tmp, prices[i] - left[i]);
ans = Math.max(ans, tmp + right[i] - prices[i]);
}
return ans;
}
}
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).
题意:给出一个数组,数组元素表示股票在第i天的股价,最多只能交易两次,求最大收益
思路:动态规划。用dp1(i)表示从0到i的最小股票值。dp2(i)表示从i到n的最大股票值。在求最大收益值时,将第一次收益的最大值加上第二次收益的最大值相加即可。
代码如下:
class Solution
{
public int maxProfit(int[] prices)
{
int len = prices.length;
if (0 == len) return 0;
int[] left = new int[len];
int[] right = new int[len];
left[0] = prices[0];
right[len - 1] = prices[len - 1];
for (int i = 1; i < len; i++)
{
left[i] = Math.min(left[i - 1], prices[i]);
}
for (int i = len - 2; i >= 0; i--)
{
right[i] = Math.max(right[i + 1], prices[i]);
}
int ans = 0;
int tmp = 0;
for (int i = 0; i < len; i++)
{
tmp = Math.max(tmp, prices[i] - left[i]);
ans = Math.max(ans, tmp + right[i] - prices[i]);
}
return ans;
}
}
相关文章推荐
- 写给明年的自己
- 统计同成绩学生人数
- 关于iTop4412启动指导
- Linux 学习笔记 gcc简单了解
- 修改字符串
- Android中Adapter初步的学习
- 寒门再难出贵子引争议
- 第18章 用于大型程序的工具
- JetBrains 系列软件
- 忘记weblogic密码
- 大一下学期的自我目标
- xmpp获取不到联系人的解决办法
- python进阶——类和对象
- spring+dwr
- [leetcode] Bulb Switcher
- onMeasure方法的使用和字体的baseline, ascent, descent
- Linux学习笔记2016/1/23 CRT配置及VI相关
- 大数据时代--Hive技术原理解析
- 小蚂蚁学习C语言(35)——两行三列二维数组变三行两列二维数组
- 数论学习