121.122.123.188. Best Time to Buy and Sell Stock I II III IV

16 篇文章 0 订阅
9 篇文章 0 订阅

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

题目:最多一次买卖

思路:动规迭代,每天比较‘历史最大收益’和(当前价-历史最小价),然后比较‘历史最小价’和‘当前价’来更新‘历史最小价’

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length<2) return 0;
        int curMin=prices[0], maxBen=0;
        for(int i = 1; i< prices.length; i++){
            maxBen = Math.max(maxBen, prices[i]-curMin);
            curMin = Math.min(curMin, prices[i]);
        }
        return maxBen;
    }
}

题目:无限多次买卖

思路:贪心,凡是有收益就卖了,再从新找‘最小价’;如果当前没收益,则更新‘最小价’。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length<2) return 0;
        int sumPro=0, minPri=prices[0];
        for(int i=1; i<prices.length; i++){
            if(prices[i]>minPri) {
                sumPro+=prices[i]-minPri;
                minPri=prices[i];
            }else{
                minPri=prices[i];
            }
        }
        return sumPro;
    }
}

题目:最多卖2次

思路:正反两次扫描,分别找到每天前后的最大利润,叠加

public int maxProfit(int[] prices) {
        if(prices==null || prices.length<2) return 0; 
        int[] proFor = new int[prices.length]; 
        int[] proBack = new int[prices.length]; 
        int result = 0; 
        //forward
        int curMin=prices[0], maxBen=0; proFor[0] = 0;  
        for(int i = 1; i< prices.length; i++){  
            maxBen = Math.max(maxBen, prices[i]-curMin);  
            proFor[i] = maxBen;
            curMin = Math.min(curMin, prices[i]);  
        }  
        //backword
        int curMax=prices[prices.length-1]; maxBen=0; proBack[prices.length-1] = 0;
        for(int i = prices.length-2; i>=0 ; i--){  
            maxBen = Math.max(maxBen, curMax - prices[i]);
            proBack[i] = maxBen;
            curMax = Math.max(curMax, prices[i]);  
        }
        for(int i=0; i<prices.length; i++){
            result = Math.max(result,proFor[i]+proBack[i]);
        }
        return result;
    }


题目:k次买卖

难题,没搞懂, 参考:
http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html
http://blog.csdn.net/linhuanmars/article/details/23236995

思路:第i天最多交易j次的最大利润dp[i][j]有三种情况:1.i天交易赔钱,所以不交易,则等于i-1天最多交易j次的最大利润dp[i-1][j],2.i天交易挣钱,a)连续挣dp[i-1][j]+diff,b) 间隔挣钱 dp[i-1][j-1]+diff


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值