122. Best Time to Buy and Sell Stock II
来源:互联网 发布:释行宇谭腿 知乎 编辑:程序博客网 时间:2024/06/07 13:51
122. Best 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 dayi.
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).
这个题在121(Best Time to Buy and Sell Stock)题的基础上增加了可以买卖多次,但是在买之前必须把之前买的卖掉。这个地方一开始我自以为是不可以同一天买卖,想了好久,后来才发现这一问题。如果,可以同一天买卖,那么对于一个递增的子序列[1,2,3,5,6,8,9],从1直接算到9(1,9)和一个数一个数(1,2)+(2,3)+(3,5)+(5,6)+(6,8)+(8,9)算到9,结果是一样的,所以只需要比较前一个数和后一个数的大小,如果后数大于前数则加两者之和,扫描到数列尾,即得结果。
class Solution {public:int maxProfit(vector<int>& prices) {int m = 0;if (prices.empty()) return m;for (int i = 0; i < prices.size() - 1; i++) if (prices[i] < prices[i + 1]) m = m + prices[i + 1] - prices[i];return m;}};
0 0
- 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- 122.Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- [LeetCode]122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- UVA 147 Dollars ( 完全背包+求解方案数精度问题)
- 【Linux】让Ubuntu 支持 GBK等字符集,解决中文乱码
- 算法导论 Exercise 2.3-5 (implement binary serach recursively)
- uva816 -- Abbott's Revenge (BFS)
- 洛谷3467 [POI2008]PLA-Postering 单调栈
- 122. Best Time to Buy and Sell Stock II
- atexit函数
- Android.mk详解
- PyQt——结合Python与Qt的GUI编程
- 《岛上书店》读后感
- css中浮动需要注意的东西
- jquery在当前点击事件函数中删除当前元素
- ubuntu 16.04 搭建LAMP开发环境
- HTTP状态码