leetcode 122 买卖股票时机

时间:2021-03-04 13:19:40   收藏:0   阅读:0

思路不是特别难,双指针就能解决问题,写的时候最大的困扰在于边界条件不清晰导致的数组越界。贴暴力代码

class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        int earn = 0;
        int n = prices.size();
        int i = 0;
        int j = 1;
        while(i<n-1 && j<n)
        {
            while(i<n-1 &&((i == 0 && prices[i]>prices[i+1]) || (i!=0 &&(prices[i]>prices[i-1] || prices[i]>prices[i+1]))))
            {
                i++;
                cout<<"ok?"<<endl;
            }
            
            while(j<n-1 && (j!=n-1 &&(prices[j]<prices[j-1] || prices[j]<prices[j+1])))
            {
                j++;
            }
            earn = earn + prices[j] - prices[i];
            i = i + 2;
            j = j + 2;
        }
        return earn;
    }
};

擦,这个贪心算法有点牛的,现在看自己的代码简直像一坨屎,贴代码

class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        int earn = 0;
        int n = prices.size();
        for(int i = 0 ; i < n-1 ; i++)
        {
            earn += max(0,prices[i+1]-prices[i]);
        }
        return earn;
    }
};

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!