Best Time to Buy and Sell Stock II
2015-06-17 20:44
288 查看
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).
解题思路:
因为本题要求我们在取得最优值的前提下,能进行更多的交易就进行更多的交易。
假设存在三个点x1, x2, x3,并且满足 x1 < x2 < x3,如果我们选x1和x3和我们选x1,x2和x2,x3获得的收益是相同的。但是当x1<x2=x3时,我们选x1和x2得到的结果不会比选x1和x3得到的结果差,因此在此处计算的时候我们采用贪心的算法。
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).
解题思路:
因为本题要求我们在取得最优值的前提下,能进行更多的交易就进行更多的交易。
假设存在三个点x1, x2, x3,并且满足 x1 < x2 < x3,如果我们选x1和x3和我们选x1,x2和x2,x3获得的收益是相同的。但是当x1<x2=x3时,我们选x1和x2得到的结果不会比选x1和x3得到的结果差,因此在此处计算的时候我们采用贪心的算法。
class Solution { public: /* 贪心求解 */ int maxProfit(vector<int>& prices) { int ans = 0; int minv; int n = prices.size(); if(n <= 1) return 0; minv = prices[0]; for(int i = 1; i < n; ++i) { if(prices[i] > minv) { ans += (prices[i] - minv); minv = prices[i]; } else { minv = min(minv, prices[i]); } } return ans; } };
相关文章推荐
- 技术选型
- [Swust OJ 610]--吉祥数
- oj刷题第一批E 对象数组求最大值
- 【hadoop】ssh localhost 免密码登陆(图解)
- shell中if语句特殊参数
- 第十四周项目2-用文件保存的学生名单
- VC中使用纯资源dll实现多语言版本
- hive中sql解析出对应表和字段的调查
- WorldWind源码剖析系列:可渲染对象类RenderableObject
- Android 学习笔记之如何实现简单相机功能
- struts的国际化理解
- 1029. Median (25)
- bzoj1005 [HNOI2008]明明的烦恼
- shell与export命令
- 第十四周项目1-小玩文件
- 第15周-阅读项目2-异常处理&&命名空间
- 每天一个linux命令(39):grep 命令
- android的数据存储方式---5种方法
- 软件工程理论阅读笔记3
- 软件工程理论阅读笔记2