Knowledge Reserve-Basic Algorithm-Greedy Algorithm

1. Greedy Algorithm

1.1 The difference between greedy algorithm and knapsack problem

The greedy algorithm can derive the global optimal through local optimality, but the knapsack problem cannot be solved and needs to be solved by dynamic programming.

1.2 Routine

Greedy algorithm has no tricks! !

The main thing is to think clearly about how to get the local optimal solution at this stage, and how to get the global optimal solution through the local optimal solution. If you can't give a counterexample, that's it.

2.leetcode questions

2.1 Question 121 - Best time to buy and sell stocks

Given an array  prices , its th  i element  prices[i] represents the price of a given stock on  i day th.

You can only choose  to buy the stock on one day  and   sell the stock on a different day in the future . Design an algorithm to calculate the maximum profit you can make.

Returns the maximum profit you can make from this trade. If you can't make any profit, return  0 .

Example 1:

Input: [7,1,5,3,6,4]
 Output: 5
 Explanation: Buy on day 2 (stock price = 1), sell on day 5 (stock price = 6), Maximum profit = 6-1 = 5. 
     Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; at the same time, you cannot sell the stock before buying.
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # 贪心算法
        # 局部最优解推出全局最优解
        # 记录最大价格和最小价格的索引,记录局部最大利润
        # 如果局部最大价格索引大于局部最小索引,更新索引,局部最大利润也更新
        max_profit = 0
        min_ind = -1
        max_ind = -1
        for i in range(1,len(prices)):
            if prices[i] > prices[i-1]:
                temp = prices[i]-prices[i-1]
                if min_ind == -1:
                    min_ind = i-1
                else:
                    if prices[i-1] < prices[min_ind]:
                        min_ind = i-1
                if max_ind == -1:
                    max_ind = i
                else:
                    if prices[i] >= prices[max_ind]:
                        max_ind = i
                if max_profit < temp:
                    max_profit = temp
                if max_profit < prices[i]-prices[min_ind]:
                    max_profit = prices[i]-prices[min_ind]
        
        return max_profit

Guess you like

Origin blog.csdn.net/Orange_sparkle/article/details/133275223