leetcode-122 Best Time to Buy and Sell Stock II
2015-04-26 21:52
447 查看
这题要求可以交易任意多次,其实就是找递增子序列
例如:1 3 4 9 5 8 2 1 3
则 9 - 1 + 8 - 5 + 3 - 1
注意条件的判断不要写错啦
discuss里面更简单的方法:感觉怪怪的
例如:1 3 4 9 5 8 2 1 3
则 9 - 1 + 8 - 5 + 3 - 1
注意条件的判断不要写错啦
<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution { public: int maxProfit(vector<int>& prices) { int len = prices.size(); if(len == 0) return 0; int maxProfit = 0; int min = prices[0]; for(int i = 1; i < len; i++){ if(prices[i] < min) min = prices[i]; else if( (prices[i] > min) && (i == len -1)){ maxProfit += prices[i] - min; }else if( (prices[i] > min) && (prices[i+1] < prices[i])){ maxProfit += prices[i] - min; min = prices[i+1]; } } return maxProfit; } };</span>
discuss里面更简单的方法:感觉怪怪的
Is this question a joke?
<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution { public: int maxProfit(vector<int>& prices) { int len = prices.size(); if(len == 0) return 0; int maxProfit = 0; for(int i = 0; i < len - 1; i++){ if(prices[i+1] > prices[i]) maxProfit += prices[i+1] - prices[i]; } return maxProfit; } };</span>
相关文章推荐
- [leetcode 122] Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II
- LeetCode122:Best Time to Buy and Sell Stock II
- leetcode: (122) Best Time to Buy and Sell Stock II
- LeetCode122 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
- Java [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
- LeetCode-122-Best Time to Buy and Sell Stock II-E
- LeetCode【122】Best Time to Buy and Sell Stock II
- [Leetcode 122, Medium] Best Time to Buy and Sell Stock II
- leetcode122~Best Time to Buy and Sell Stock II
- [LeetCode122]Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II
- leetcode_c++:Best Time to Buy and Sell Stock II(122)
- Leetcode算法学习日志-122 Best Time to Buy and Sell Stock II
- leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV