leetcode [Best Time to Buy and Sell Stock II]//待整理多种解法
2017-03-29 22:01
489 查看
class Solution { public int maxProfit(int[] prices) { int res = 0; int low = 0, high = 0; if(prices.length == 0) return 0; high = prices[prices.length - 1]; low = prices[prices.length - 1]; for(int i = prices.length - 2; i >= 0; i--){ //从后往前找,贪心算法,确保每一次出售都是能出售的最大差价 //正确性:每次出售找到比low还low的,只这出售这一次比多次出售要多,因为出售多次也只是出售一次的一个子集,中间还不包括完 //如:1,4,7,10,;出售多次:(1,4)(7,10)总价值为6,出售一次(1,10)总价值为9 if(prices[i] < low) low = prices[i];//往前找比low还low的进价 if(prices[i] > low){//找到比low大的就将前面的出售 res += high - low;//出售,加入res high = low = prices[i];//调整新的一次出售 } } res += high - low;//防止还有循环到最前面没加进res的,循环体外要加一句这个 return res; } }
相关文章推荐
- leetcode [Best Time to Buy and Sell Stock]//待整理多种解法
- [LeetCode] 递推思想的美妙 Best Time to Buy and Sell Stock I, II, III O(n) 解法
- 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 Solution
- 【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 61: Best Time to Buy and Sell Stock II
- [Leetcode 51] 122 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 I II III
- [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