买卖股票的最大利润 (leetcode121)

一:解题思路

这个题目有2种解法。第一种为暴力破解法,求出所有可能的情况,然后得到最大值。Time:O(n^2)。Space:O(1)

第二种方法,采用动态规划的思想。Time:O(n),Space:O(1)

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

第一种方法C++:

class Solution
{
public:
    int max(int a, int b) { return a > b ? a : b; }

    int maxProfit(vector<int>& prices)
    {
        int maxPrice = 0;

        if (prices.size() < 2) return 0;

        for (int i = 0; i < prices.size(); i++)
        {
            for (int j = i + 1; j < prices.size(); j++)
            {
                maxPrice = max(maxPrice, (prices[j] - prices[i]));
            }
        }

        return maxPrice;
    }
};

第一种方法Java:

class Solution
{
    public int maxProfit(int[] prices)
    {
        int maxPrices=0;

        if(prices.length<2) return 0;
        
        for(int i=0;i<prices.length;i++)
        {
            for(int j=i+1;j<prices.length;j++)
            {
                maxPrices=Math.max(maxPrices,(prices[j]-prices[i]));
            }
        }

        return maxPrices;
    }
}

第二种方法C++:

class Solution 
{
public:
    int max(int a, int b) { return a > b ? a : b; }

    int maxProfit(vector<int>& prices) 
    {
        if (prices.size() < 2) return 0;

        int maxProfit = 0;
        int buy = prices[0];

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

        return maxProfit;
    }
};

第二种方法Java:

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

           for(int i=1;i<prices.length;i++)
           {
               if(prices[i]<buy)
               {
                   buy=prices[i];
               }
               else
               {
                   maxProfit=Math.max(maxProfit,(prices[i]-buy));
               }
           }

           return maxProfit;
    }
}

 

Python方法一:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxProfits=0
        n=len(prices)

        for i in range(0,n):
            for j in range(i+1,n):
                maxProfits=max(maxProfits,prices[j]-prices[i])

        return maxProfits

Python方法二:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxProfits=0
        n=len(prices)
        if n<2:
            return 0
        buy=prices[0]
        for i in range(1,n):
            if prices[i]<buy:
                buy=prices[i]
            else:
                maxProfits=max(maxProfits,prices[i]-buy)
        
        return maxProfits

 

posted @ 2020-03-15 14:22  repinkply  阅读(383)  评论(0)    收藏  举报