Best Time to Buy and Sell Stock I
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
这道题非常简单,在每个位置卖的话,它能获得的最大值就是它的值减去在它之前出现的最小值。
如果在它之前没有比它小的值,那么就是当天买当天卖,即profit为0。所以就不断更新已出现过的数中最小的,然后算在每一天卖,能获得的最大利润,然后对比出总体能获得的最大利润。时间复杂度O(n)
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0) return 0;
int low = prices[0];
int maxProfit = Integer.MIN_VALUE;
for(int i=0; i<prices.length; i++){
if(prices[i]<low) low = prices[i];
int profit = prices[i]-low;
if(profit>maxProfit) maxProfit = profit;
}
return maxProfit;
}
}
Best Time to Buy and Sell Stock II
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
这道题因为可以买卖无数次,因此就是不断寻找递增数列就就行(greedy),start是递增数列的第一个值,当递增数列结束,start就从下一个数重新开始找递增数列。需要注意的是,当递增序列一直找到最后一个数时,就不用再往下了,把当前的profit加到总profit就可以了,如果没有这步,就会漏算最后一个递增序列的Profit, 代码如下:
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0) return 0;
int profit = 0;
int start = prices[0];
for(int i=1; i<prices.length; i++){
if(prices[i]>=prices[i-1]){
if(i==(prices.length-1)) profit += prices[i]-start; //到最后一个数时,把当前的Profit加到总profit里面
else continue;
}
else{
profit+= prices[i-1]-start;
start = prices[i];
}
}
return profit;
}
}
时间复杂度O(n)
Best Time to Buy and Sell Stock III
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
这道题就是把一个数组分成两部分,查看每部分可以获得的最大profit。并且每个点都可以作为分割点。
因此,有两个数组,left[i]是[0, i]天中能活得的最大利润,right[i]是i到最后一天中能活得的最大利润。
循环中保存遇到的前面的最小值和后面的最大值。
left[i] = max(left[i-1], left[i]-min)
right[i] = max(right[i+1], max-right[i])
由于在[0, i]和[i, end]天内得到的最大利润不一定要在第i天买入卖出,因此要比较之前已经获得的最大利润,和在当天买入或卖出能获得的最大利润,然后取大的那个。
代码如下:
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length==0) return 0;
int[] left = new int[prices.length]; //best profit we can get during [0, i] day
int[] right = new int[prices.length]; //best profit we can get during [i, end] day
left[0] = 0;
int min = prices[0];
for(int i=1; i<prices.length; i++){
if(prices[i]<min) min = prices[i];
left[i] = Math.max(left[i-1], prices[i]-min);
}
int max = prices[prices.length-1];
right[prices.length-1] = 0;
for(int i= (prices.length-2); i>=0; i--){
if(prices[i] > max) max = prices[i];
right[i] = Math.max(right[i+1], max- prices[i]);
}
int maxprofit = 0;
for(int i=0; i<prices.length; i++){
maxprofit = Math.max(maxprofit, (left[i]+right[i]));
}
return maxprofit;
}
}
Best Time to Buy and Sell Stock IV
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
这个系列简直了,居然这么多题。这道题还没做,做了来更新!