LeetCode(122) Best Time to Buy and Sell Stock II
2015-10-30 16:22
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 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
分析
买卖股票II,与 LeetCode(121) Best Time to Buy and Sell Stock的区别就是,此次允许买卖多次,但是必须卖出后才可下次买入。实际上是求股价波浪线的所有上升段的长度和。
AC代码
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; int sum = 0; //只要后项比前项大,这部分值就一定可以变为利润 for (size_t i = 1; i < prices.size(); ++i) { if (prices[i] > prices[i - 1]) sum += (prices[i] - prices[i - 1]); } return sum; } };
GitHub测试程序源码
相关文章推荐
- 如何快速把多个excel表合并成一个excel表
- Python按行读文件
- Android 开发实用方法大全
- LeetCode(122) Best Time to Buy and Sell Stock II
- Win32程序标准开发流程 .
- 解决:IE浏览器打开就自动最小化,无法打开
- 实现lucene来进行全文索引查找
- 有向图
- Ubuntu14.04 安装PIL(Image) Package
- 微信页面如何测试
- Eclipsez安装GEF
- https证书 wamp2.5 配置单双向SSL证书
- php验证邮箱和ip地址最简单方法汇总
- 网站开发进阶(九)系统内存检测
- linux 批量ssh认证
- 网站开发进阶(九)系统内存检测
- xcode升级后, 插件失效修复
- IOS开发中有用的第三方库
- Android Https相关完全解析 当OkHttp遇到Https
- LeetCode 190: Reverse Bits