Best Time to Buy and Sell Stock III ---- LeetCode


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

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


解题思路:大概:使用动态规划解决该问题。

                   将数组分成两段,分别计算出每段的最大利润,然后相加与之交易一次的最大利润作比较,最后输出最大值。

            具体:

            1.计算交易一次的最大利润max:从左到右遍历数组,计算每个i位置的最大利润同时将利润值保存在数组maxLeft

            2.从右到左遍历数组:将数组分成两段:1~i,i~length-1,1~i段的最大利润值maxLeft[i],计算i~length-1的最大利润

              同时保存在数组maxRight中,计算maxRight[i]与maxLeft[i]的值,若该值比max大则将其赋值给max。


public class Solution {
    public int maxProfit(int[] prices) {
           int max=0;
           int length=prices.length;
           if(length<=1){
         return max;   
           }
           int [] maxLeft=new int[length];
           int lowest=prices[0];
           maxLeft[0]=0;
           for(int i=1;i<length;i++){
          if(lowest<prices[i]){
         int profit=prices[i]-lowest;
         if(profit>maxLeft[i-1]){
         maxLeft[i]=profit;
         }else{
         maxLeft[i]=maxLeft[i-1];
         }
          }else{
         lowest=prices[i];
         maxLeft[i]=maxLeft[i-1];           
          }       
           }
           max=maxLeft[length-1];
           
           int [] maxRight=new int[length];
           int high=prices[length-1];
           maxRight[length-1]=0;
           for(int i=length-2;i>=0;i--){
          if(prices[i]<high){
          int profit=high-prices[i];
                   if(profit>maxRight[i+1]){
                  maxRight[i]=profit;                 
                   }else{
                  maxRight[i]=maxRight[i+1];
                   }         
          }else{
          high=prices[i]; 
          maxRight[i]=maxRight[i+1];
          }
              int sum=maxLeft[i]+maxRight[i];
         if(sum>max){
         max=sum;
         }  
           }
                     
           return max;
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值