[leetcode] 122.Best Time to Buy and Sell Stock II 动归 or 贪心
2016-03-27 10:25
253 查看
Sell[i]表示第i天卖出其最大利润,有公式,buy[i]=max{sell[1]..sell[i-1]}-a[i]; sell[i]=max{buy[1]..buy[i-1]}+a[i]
public class Solution {
public int maxProfit(int[] prices) {
int l=prices.length+1;
int[] buy=new int[l];
int[] sell=new int[l];
sell[0]=0;
buy[0]=Integer.MIN_VALUE;
int maxsell=sell[0];
int maxbuy=buy[0];
for(int i=1;i<=prices.length;i++){
sell[i]=maxbuy+prices[i-1];
if (sell[i]>maxsell) maxsell=sell[i];
buy[i]=maxsell-prices[i-1];
if (buy[i]>maxbuy) maxbuy=buy[i];
}
return maxsell;
}
}
2.后来想了想似乎没那么麻烦,直接贪心就可以了,找到一个连续递减序列的最小的,然后再找到一个连续递增最大的,相减就是这段可以获得最大利润。
public int maxProfit(int[] prices) {
int profit = 0, i = 0;
while (i < prices.length) {
while (i < prices.length-1 && prices[i+1] <= prices[i]) i++;
int min = prices[i++];
// find next local maximum
while (i < prices.length-1 && prices[i+1] >= prices[i]) i++;
profit += i < prices.length ? prices[i++] - min : 0;
}
return profit;
}
3.看了下mostvotes,发现了这个更简洁的做法,有人说这种方法是假定了可以同一天买和卖,其实不对,比如三天的价格是1,2,5,最多能挣5-1,等于(2-1)+(5-2)其实是一种等效,并不是一定在同一天买了又卖。
public class Solution {
public int maxProfit(int[] prices) {
int total = 0;
for (int i=0; i< prices.length-1; i++) {
if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i];
}
return total;
}
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- C++动态规划之最长公子序列实例
- C++动态规划之背包问题解决方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析