股票最大收益 Best Time to Buy and Sell Stock II
2013-11-06 19:39
435 查看
题目源自于leetcode。
题目: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).
思路:假设这把这些点连起来看出折现,观察发现,获得最大收益的方法是每次都在极小值买入,在极大值卖出。
第一个点:如果一开始就在增长,则第一个点是极小值。
最后一点:如果最后是在增长,则最后一个点是极大值。
实际的代码中已经把两端的特殊情况包含在内了。
代码:
题目: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 num = prices.size(); if(num <= 1) return 0; int sum =0; int min, max; int i=0; while(i < num) { while((i+1<num) && (prices[i] > prices[i+1])) i++; min = prices[i]; while((i+1<num) && (prices[i] < prices[i+1])) i++; max = prices[i]; sum += max - min; i++; } return sum; } };注意:代码写完后要认真检查,返回值不能丢,变量初始化不能丢,输入合法性检查不能忘记。
相关文章推荐
- Delphi视频教程:黑客基地delphi特训班
- NumPy学习笔记--入门篇
- 最大连续和
- uml之活动图
- ios中UIScrollview和Tableviewde 的嵌套使用
- Linux创建LVM
- linux apache下虚拟主机配置方法
- TCMalloc介绍
- Code Forces 242 B. Big Segment 贪心
- Linq To Entities 及其相关
- 政府、公积金服务电话
- IDA调试基础------断点
- 剩女
- org.apache.commons.lang.exception.NestableRunti...
- Android菜鸟笔记-Android平板实现全屏模式隐藏虚拟键和状态栏
- Zju2492 A Dp Problem
- Flex4 初始化过慢解决方法
- 如何完全卸载 MySQL
- UVa 10719 Quotient Polynomial
- chmod命令详细用法