leetcode-121-Best Time to Buy and Sell Stock

问题

题目:[leetcode-121]

思路

蛮力法,计算所有可能的情形。 O(N2) 的复杂度。

代码(TLE)

class Solutiocn {
public:
    int maxProfit(vector<int>& prices) {
        int sz = prices.size();
        if(!sz) return 0;

        int ans = 0;
        for(int i = 0; i < sz; ++i){
            for(int j = i + 1; j < sz; ++j){
                int profix = prices[j] - prices[i];
                ans = std::max(ans, profix);
            }
        }
        return ans;
    }
};

思路1

看了最长连续字段和的代码。有点启发。首先这两个问题本质都是找一个区间,虽然后面这个其实不是找区间。但是需要找到start,end两个下标。
既然,前面的题目都可以解。这个题我觉得应该也可以。
对比之前的思路,一定要考虑当前数值和之前数值的关系,我就是按着这个方向才想到了解决办法。O(N)的复杂度。DP求解。

当然,我下面你的做法还是标记了买入点和卖出点。最大字段和是没有明确的标记,它是当dp[i-1]<=0时,重新计算。就相当于标记了开始点。

定义:dp[i]表示在第i点卖出时的利润,则状态转移函数如下:

dp[i]={prices[i]prices[buy]1 and buy=i, prices[buy]<prices[i], prices[buy]prices[i] (1)

代码1

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int sz = prices.size();
        if(!sz) return 0;

        int buy = 0;
        int max = 0;
        std::vector<int> dp(sz, int());
        dp[0] = -1;
        for(int i = 1; i < sz; ++i){
            if(prices[buy] < prices[i])
                dp[i] = prices[i] - prices[buy];
            else{
                buy = i;
                dp[i] = -1;
            }
            max = std::max(max, dp[i]);
        }
        return max;
    }
};

代码2

省去空间的开销。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int sz = prices.size();
        if(!sz) return 0;

        int buy = 0;
        int max = 0;
        int profit = -1;

        for(int i = 1; i < sz; ++i){

            if(prices[buy] < prices[i])
                profit = prices[i] - prices[buy];
            else{
                buy = i;
                profit = -1;
            }
            max = std::max(max, profit);
        }
        return max;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值