[leetcode] Best Time to Buy and Sell Stock II
来源:互联网 发布:vb.net 新建文件夹 编辑:程序博客网 时间:2024/05/29 11:13
1.Description
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).
2.Analyse:
e.g. array: 5 3 2 1 6 7 9
So we should buy at 1, sell at 9 and have profit 9 -1 = 8.
That's to say we should buy at valley and sell at peak.
How to tell valley and peak? --->f(x)'s slope using g(x)
Definition: if f(x) == f(x-1) , g(x) = 0;
f(x) > f(x-1), g(x) = 1;
f(x) < f(x-1), g(x) = -1;
valley is the point where g(x) turn to 1 from 0 or -1;
peak is the point where g(x) turn to -1 from 0 or 1;
Then, we should buy first and then sell. so we need a flag to indicate the operation.
At last, if we have a stock on our hand, we need to sell the stock.
NOTE: f(x) = f(x-1).......
3 Code:
int maxProfit(vector<int> &prices) { if(prices.size() <= 1) { return 0; } const int BUY = 1;//1 for buy -1 for sell const int SELL = -1; int profit = 0; int pre = 0; int cur = 0; int operation = BUY; std::vector<int>::iterator it; for (it = prices.begin()+1; it != prices.end() ; ++it) { if (*it > *(it - 1)) { pre = cur; cur = 1; } else if (*it < *(it - 1)) { pre = cur; cur = -1; } else { pre = cur; cur = 0; } if (pre < cur && cur == 1 && operation == BUY) { profit -= *(it - 1); operation = SELL; } if (pre > cur && cur == -1 && operation == SELL) { profit += *(it -1); operation = BUY; } } if (operation == SELL) { profit += *(--it); } return profit; }
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [Leetcode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- LeetCode-Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock II
- java中判断字符串是否为数字的三种方法
- 外部排序
- Calendar.set用法的深入探讨
- CodeForces 414B--Mashmokh and ACM (dp)
- Namenode recovery, How does namenode recovery works?
- [leetcode] Best Time to Buy and Sell Stock II
- 黑马程序员 第23天 异常总结
- Flex4 List项 增加 删除 变色等简单实现
- windows编程之自订资源
- JavaScript和Android代码相互调用
- POJ 1698 Alice's Chance
- asp.net上传的图片保存到文件夹下,并且生成缩略图
- 工作流产品标准
- install google chrome on ubuntu