leetcode刷题。总结,记录,备忘 122
2015-07-26 14:43
309 查看
leetcode刷题122Best Time to Buy and Sell Stock II
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).
这个题其实很简单,感觉比 I 版都简单点,就是允许多次购买,然后计算总数,所以只需要计算每个连续的升序的序列的头尾差值,然后相加得到总和即可。
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).
这个题其实很简单,感觉比 I 版都简单点,就是允许多次购买,然后计算总数,所以只需要计算每个连续的升序的序列的头尾差值,然后相加得到总和即可。
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() == 0) return 0; int min = *prices.begin(); int temp = 0, sum = 0; for (vector<int>::iterator it =prices.begin(); it != prices.end()-1; ++it) { if (*it > *(it+1)) { min = *(it+1); sum += temp; temp = 0; continue; } else { temp = *(it+1) - min; } } sum += temp; return sum; } };
相关文章推荐
- DFS
- assert()函数用法总结
- 设计4个线程 其中两个线程每次对j增加1
- MYSQL---自定义函数
- [转载] 在Windows上将Apache Portable Runtime (APR)编译为DLL
- Nginx 笔记与总结(4)配置 server 访问日志
- [DT大数据梦工厂]-scala-helloworl的解析
- JS/Jquery的一些技巧
- windows 下常用端口
- 基于Cocos2d-x的英雄联盟皮肤选择菜单
- Android下利用zbar类库实现扫一扫
- iOS Human Interface Guidelines(原创翻译)第三章
- 传苹果今年推iPad mini4 相当于微缩版Air2
- HDU 1372 Knight Moves(BFS)
- SVN添加文件时的错误处理:...\conf\svnserve.conf:12: Option expected
- uva439_骑士的移动
- lucence分词器
- 什么是虚拟内存
- Windows2008R2允许多用户远程登录设置
- Objective-C反射机制