*[Lintcode] 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 twotransactions.

Example

Given an example [4,4,6,1,1,4,2,5], return 6.

与前几题不同,这道题需要同时考虑左侧区间和右侧区间共同的最大值。可以创建两个数组, 一个包做index左侧最大的获利值,一个数组保存index右侧最大的获利值。最后计算两个数组每个位置的值,取最大值即为结果


class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        int[] left = new int[prices.length];
        int[] right = new int[prices.length];
        
        int min = Integer.MAX_VALUE, temp = 0;
        for(int i = 0; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            left[i] = Math.max(prices[i] - min, temp);
            temp = Math.max(temp, left[i]);
        }
        int max = Integer.MIN_VALUE;
        int res = 0;
        temp = 0;
        for(int i = prices.length - 1; i >= 0; i--) {
            max = Math.max(max, prices[i]);
            right[i] = Math.max(max - prices[i], temp);
            temp = Math.max(temp, right[i]);
                
            res = Math.max(res, left[i] + right[i]);
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值