LeetCode Best Time to Buy and Sell Stock(dp)
2016-01-23 21:20
267 查看
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
题意:给出一个数组,每个元素表示股票在第i天的价钱
思路:用动态规划。用dp(i)表示从第i个到第n天的最大的价钱,状态转移方程为dp(i) = max{dp(i +1),price[i]}
代码如下:
class Solution
{
public int maxProfit(int[] prices)
{
int len = prices.length;
if (0 == len) return 0;
int ans = 0;
int max = prices[len - 1];
for (int i = len - 1; i >= 0; i--)
{
ans = Math.max(max - prices[i], ans);
if (prices[i] > max)
{
max = prices[i];
}
}
return ans;
}
}
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
题意:给出一个数组,每个元素表示股票在第i天的价钱
思路:用动态规划。用dp(i)表示从第i个到第n天的最大的价钱,状态转移方程为dp(i) = max{dp(i +1),price[i]}
代码如下:
class Solution
{
public int maxProfit(int[] prices)
{
int len = prices.length;
if (0 == len) return 0;
int ans = 0;
int max = prices[len - 1];
for (int i = len - 1; i >= 0; i--)
{
ans = Math.max(max - prices[i], ans);
if (prices[i] > max)
{
max = prices[i];
}
}
return ans;
}
}
相关文章推荐
- TabLayout+Fragment+ViewPager+FragmentStatePagerAdapter实现Tab标签
- HDU 2095 find your present (2)
- Visio2010建立ER图并直接导出为SQL语句 .
- Weka数据挖掘——选择属性
- Oracle批量执行sql语句之禁用所有表的外键
- 数的概念
- JVM-OutOfMemory异常重现
- linux命令学习之(tail)
- RT-Thread的线程(任务)处理【RT-Thread学习笔记 2】
- 160110 ~ 160117总结 —— 毕姥爷的题
- Python基础之day2
- 快到这段时间的终点了。。。
- 如何很好的Review自己的代码
- swift手记-4
- Android事件分发机制简述
- poj2253 Frogger 克鲁斯卡尔变种算最小生成树最大边
- JavaScript、jQuery、HTML5、Node.js实例大全-读书笔记2
- TSL三态门_20160119
- 关于 [UITableView _configureCellForDisplay:forIndexPath:]断言失败问题接解决
- helloworld