[LeetCode] Best Time to Buy and Sell Stock II
2015-08-13 17:04
639 查看
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).
解题思路:
题意为给定每天的股价,你可以进行任何次数的交易,但是不能同时拥有多个股。要求最大的利润是多少。
我们可以在每个波谷的时候买进,每个波峰的时候卖出,这样的利润最大。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len==0 || len==1){
return 0;
}
int result = 0;
for(int i=1; i<len; i++){
if(prices[i]>prices[i-1]){
result += prices[i] - prices[i-1];
}
}
return result;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解