您的位置:首页 > 其它

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: