LeetCode 121. Best Time to Buy and Sell Stock

 121. Best Time to Buy and Sell Stock

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

题目大致意思:

       给你一个数组代表股票每日的价格,你最多可以交易一次股票价格(可以不交易), 只能按照先买入后卖出的的顺序交易。求出最大的股票交易获利

解题思路:

     主要方法:动态规划  设dp[i] 表示第i天交易获利的值, 其中 dp[0] = 0 (第一天交易或者不交易都为0  一天内股价不变) 

min 代表第一天开始到第i天的最低股票价格. 我们只需要维护这个dp数组 便可求解.

     分析: 每日的股价分为如下三种种情况

            (1) 今日股价大于昨日股价考虑交易  交易获利:prices[i] - min,  昨日获利 dp[i-1] 取两者的最大值

                                     dp[i] = Math.max( dp[i-1], prices[i] - min);

               (2) 今日估计小于昨日股价  不交易(傻瓜才会交易) 即 按照昨日的股价作为最大的获利 

                                     dp[i] = dp[i-1];

              (3)  今日股价等于昨日股价 : 交易或者不交易 与昨日收益一样 同(2)

                                    dp[i] = dp[i-1];

  附上代码 :

public int maxProfit(int[] prices) {
        if(prices.length == 0) return  0;
        int[] dp = new int[prices.length];
        dp[0] = 0;
        int min = prices[0];
        for(int i = 1; i < prices.length; i ++){
            if(min > prices[i]) min = prices[i];
            if(prices[i] > prices[i-1]){
                dp[i] = Math.max( dp[i-1], prices[i] - min);
            }else {
                dp[i] += dp[i-1];
            }
        }
        return  dp[prices.length-1];
    }

   注: 限作者水平有限,有任何问题欢迎评论区留言或者私信。欢迎幸福的骚扰

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值