leetcode--best_time_to_buy_and_sell_stock

33 篇文章 0 订阅
27 篇文章 0 订阅

best_time_to_buy_and_sell_stock_i

题意:用一个数组表示股票每天的价格,数组 prices 的第i个数 prices[i] 表示股票在第i天的价格。 如果只允许进行一次交易,也就是说只允许买一支股票并卖掉,求最大的收益。

分析:动态规划法。从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求。递推式为 maxProfit(n)=max(prices[i]min(prices[0...i1])),1in

代码:时间O(n),空间O(1)。

public int maxProfit(int[] prices) {
        int length = prices.length;
        if(length == 0 || length == 1){
            return 0;
        }else{
            int min = prices[0];
            int max = 0;
            for(int i = 1; i < length; i++){
                if(prices[i] < min){
                    min = prices[i];
                }else{
                    max = (max > (prices[i] - min)) ? max : (prices[i] - min);
                }
            }
            return max;
        }
    }

python程序(注:本程序与上述解题思路不一致,写复杂了。)

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        maxList = [0 for i in range(0, len(prices))]
        for i in range(len(prices) - 1, -1, -1):
            if i == len(prices) - 1:
                maxList[len(prices) - 1] = prices[len(prices) - 1]
            else:
                if prices[i] > maxList[i + 1]:
                    maxList[i] = prices[i]
                else:
                    maxList[i] = maxList[i + 1]
        maxProfits = []
        for j in range(len(prices)):
            if j < len(prices) - 1:
                maxProfits.append(maxList[j + 1] - prices[j])
            else:
                maxProfits.append(0)
        result = 0
        for k in range(len(maxProfits)):
            if maxProfits[k] > result:
                result = maxProfits[k]
        return result

if __name__ == '__main__':
    temp = input('please enter a list: ')
    prices = [int(price) for price in temp.split(' ')]
print(Solution().maxProfit(prices))

源程序下载地址

best_time_to_buy_and_sell_stock_ii

题目:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。交易次数不限,但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。

分析:贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格,就算入收益。

代码:时间O(n),空间O(1)。

public class best_time_to_buy_and_sell_stock_II {
     public int maxProfit(int[] prices) {
            int sum = 0;
            for(int i = 0; i < prices.length - 1; i++){
                if(prices[i + 1] > prices[i]){
                    sum += (prices[i + 1] - prices[i]);
                }
            }
            return sum;
        }
}

源程序下载地址

best_time_to_buy_and_sell_stock_iii

题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易两次,手上最多只能持有一支股票,求最大收益。

分析:动态规划法。以第i天为分界线,计算第i天之前进行一次交易的最大收益preProfit[i],和第i天之后进行一次交易的最大收益postProfit[i],最后遍历一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。第i天之前和第i天之后进行一次的最大收益求法同Best Time to Buy and Sell Stock I。

代码:时间O(n),空间O(n)。

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) return 0;

        int n = prices.length;
        int[] preProfit = new int[n];
        int[] postProfit = new int[n];

        int curMin = prices[0];
        for (int i = 1; i < n; i++) {
            curMin = Math.min(curMin, prices[i]);
            preProfit[i] = Math.max(preProfit[i - 1], prices[i] - curMin);
        }

        int curMax = prices[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            curMax = Math.max(curMax, prices[i]);
            postProfit[i] = Math.max(postProfit[i + 1], curMax - prices[i]);
        }

        int maxProfit = 0;
        for (int i = 0; i < n; i++) {
            maxProfit = Math.max(maxProfit, preProfit[i] + postProfit[i]);
        }

        return  maxProfit;
    }
}

best_time_to_buy_and_sell_stock_iiii

题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易k次,手上最多只能持有一支股票,求最大收益。

分析:特殊动态规划法。传统的动态规划我们会这样想,到第i天时进行j次交易的最大收益,要么等于到第i-1天时进行j次交易的最大收益(第i天价格低于第i-1天的价格),要么等于到第i-1天时进行j-1次交易,然后第i天进行一次交易(第i天价格高于第i-1天价格时)。于是得到动规方程如下(其中diff = prices[i] – prices[i – 1]):

profit[i][j] = max(profit[i – 1][j], profit[i – 1][j – 1] + diff)

看起来很有道理,但其实不对,为什么不对呢?因为diff是第i天和第i-1天的差额收益,如果第i-1天当天本身也有交易呢,那么这两次交易就可以合为一次交易,这样profit[i – 1][j – 1] + diff实际上只进行了j-1次交易,而不是最多可以的j次,这样得到的最大收益就小了。

那么怎样计算第i天进行交易的情况的最大收益,才会避免少计算一次交易呢?我们用一个局部最优解和全局最有解表示到第i天进行j次的收益,这就是该动态规划的特殊之处。

用local[i][j]表示到达第i天时,最多进行j次交易的局部最优解;用global[i][j]表示到达第i天时,最多进行j次的全局最优解。它们二者的关系如下(其中diff = prices[i] – prices[i – 1]):

local[i][j] = max(global[i – 1][j – 1] + max(diff, 0), local[i – 1][j] + diff)
global[i][j] = max(global[i – 1][j], local[i][j])

其中的local[i – 1][j] + diff就是为了避免第i天交易和第i-1天交易合并成一次交易而少一次交易收益。

转载自 http://blog.csdn.net/ljiabin/article/details/44900389

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值