Best Time to Buy and Sell Stock III

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).

与前两题相比 更改了要求 只能进行一次或者两次操作 故可以将其分为左右两部分 各视为一次操作 当左边或右边为0时  就相当于操作一次  然后分别求得两半边的profit最大值 进行相加得到总值  最后进行一次比较即可得出结果  具体写时 左右各建一个数组lpro  rpro 分别存储profit值 注意的是 左右两边的数组值只要一次遍历即可得到 因为前后有关联 lpro[i]=max(lpro[i-1],pricrs[i]-min); 右边的 rpro[i]=max(rpro[i+1],max-prices[i]); 代码如下;

public class Solution {
    public int maxProfit(int[] prices) {
       if(prices.length<=1)return 0;
		int[] lpro=new int[prices.length];
        int[] rpro=new int[prices.length];
        int min=prices[0];
        lpro[0]=0;
        for(int i=1;i<prices.length;i++){
			if(min>prices[i])min=prices[i];
			lpro[i]=Math.max(lpro[i-1],prices[i]-min);
		}
        rpro[prices.length-1]=0;
        int max=prices[prices.length-1];
        for(int i=prices.length-2;i>=0;i--){
        	if(max<prices[i])max=prices[i];
        	rpro[i]=Math.max(rpro[i+1], max-prices[i]);
        }
        int res=0;
        for(int i=0;i<prices.length;i++){
        	if(lpro[i]+rpro[i]>res)res=lpro[i]+rpro[i];
        }
        return res;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值