122. Best Time to Buy and Sell Stock II
2016-07-10 17:33
337 查看
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).
Subscribe to see which companies asked this question
我的做法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum=0;
if(prices.size()==0) return 0;
int pre=prices[0];
for(int i=1;i<prices.size();++i)
{
if(prices[i]>pre)
{
sum+=(prices[i]-pre);
pre=prices[i];
}
else
{
pre=prices[i];
}
}
return sum;
}
};
更简洁代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ret=0;
for(int i=1;i<prices.size();++i)
ret+=max(prices[i]-prices[i-1],0);
return ret;
}
};
i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).
Subscribe to see which companies asked this question
我的做法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum=0;
if(prices.size()==0) return 0;
int pre=prices[0];
for(int i=1;i<prices.size();++i)
{
if(prices[i]>pre)
{
sum+=(prices[i]-pre);
pre=prices[i];
}
else
{
pre=prices[i];
}
}
return sum;
}
};
更简洁代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ret=0;
for(int i=1;i<prices.size();++i)
ret+=max(prices[i]-prices[i-1],0);
return ret;
}
};
相关文章推荐
- 【Android基础】 Launch Mode
- Separating Pebbles数学,暴力
- Spring ApplicationContext的国际化支持
- 中文分词词性对照表
- Java隐式类型转换
- spring + springMVC + spring Data + jpa + maven 项目框架搭建
- 程序员面试金典题解 二叉树平衡检查
- LVM逻辑盘扩容实例
- iOS开发——响应链(Responder Chain)的深入理解和代码示例(二)
- php实现简单的SQL Builder
- float和position
- Nodejs创建Express4项目以及使用Visual Studio Code编辑器配置Nodejs开发环境
- CodeForces 682C - Alyona and the Tree(dfs)
- JVM内存区域划分 EDEN SPACE、SURVIVOR SPACE、TENURED GEN
- Python学习笔记9:Python文件和输入输出
- SpringMVC注解
- Java虚拟机体系结构分析
- CSDN寄过来的两本书
- 优化MySQL数据库性能的八大方法
- PHP中global与$GLOBALS['']的区别