p64 不限次数进行股票买卖的最大利润 (leetcode 122)

一:解题思路

方法一:不断的寻找股票的最小值和最大值,并在最小值得时候买入,在最大值得时候卖出。Time:O(n),Space:O(1)

方法二:贪心法,只要后一天的值大于前一天的值,那么就进行买卖。Time:O(n),Space:O(n)

二:完整代码示例 (C++版和Java版)

方法一C++:

class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        if (prices.size() == 0) return 0;
        int n = prices.size();
        int i = 0, buy = 0, sell = 0,maxProfit=0;

        while (i < n - 1)
        {
            while (i < n - 1 && prices[i + 1] <= prices[i]) i++;
            buy = prices[i];
            while (i < n - 1 && prices[i + 1] >= prices[i]) i++;
            sell = prices[i];

            maxProfit += (sell-buy);
        }

        return maxProfit;
    }
};

方法一Java:

class Solution {
    public int maxProfit(int[] prices)
    {
           if(prices==null||prices.length==0) return 0;
           int maxProfit=0,i=0,buy=0,sell=0;
           int n=prices.length;
           
           while(i<n-1)
           {
               while(i<n-1 && prices[i+1]<=prices[i]) i++;
               buy=prices[i];
               while(i<n-1 && prices[i+1]>=prices[i]) i++;
               sell=prices[i];
               
               maxProfit+=(sell-buy);
           }
           
           return maxProfit;
    }
}

方法二C++:

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

        for (int i = 1; i < prices.size(); i++)
        {
            if (prices[i] > prices[i - 1])
                maxProfit += (prices[i]-prices[i-1]);
        }

        return maxProfit;
    }
};

方法二Java:

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

           return maxProfit;
    }
}

猜你喜欢

转载自www.cnblogs.com/repinkply/p/12527154.html
今日推荐