• 122. 买卖股票的最佳时机II


    1. 暴力法

      计算所有可能的交易组合相对应的利润,并找出它们其中的最大利润。

      • Python3

        class Solution:
            def maxProfit(self, prices: List[int]) -> int:
                return self.calculate(prices, 0)
        
            def calculate(self, prices, s):
                if s >= len(prices):
                    return 0
        
                max = 0
                for start in range(s, len(prices)):
                    max_profit = 0
                    for i in range(start+1, len(prices)):
                        if prices[start] < prices[i]:
                            profit = self.calculate(prices, i+1) + prices[i] - prices[start]
                            if profit > max_profit:
                                max_profit = profit
                    if max_profit > max:
                        max = max_profit
                return max
        
      • Go

        func maxProfit(prices []int) int {
            return cal(prices, 0)
        }
        
        func cal(prices []int, s int) int {
            if s > len(prices) {
                return 0
            }
            max := 0
            for i := s; i < len(prices); i++ {
                maxprices := 0
                for j := i+1; j < len(prices); j++ {
                    if prices[i] < prices[j]{
                        pro := (prices[j] - prices[i]) + cal(prices, j+1)
                        if pro > maxprices {
                            maxprices = pro
                        }
                    }
        
                }
                if max < maxprices {
                    max = maxprices
                }
            }
            return max
        }
        
    2. 贪心法

      • 从第 i 天(这里 i >= 1)开始,与第 i - 1 的股价进行比较,如果股价有上升(严格上升),就将升高的股价( prices[i] - prices[i- 1] )记入总利润,按照这种算法,得到的结果就是符合题意的最大利润。

      • Python

        class Solution:
            def maxProfit(self, prices: List[int]) -> int:
                max_profit = 0
                for i in range(1, len(prices)):
                    if prices[i] > prices[i-1]:
                        max_profit += prices[i] - prices[i-1]
                return max_profit
        
      • Go

        func maxProfit(prices []int) int {
            max := 0
            for i :=1; i<len(prices); i++{
                if prices[i] > prices[i-1]{
                    max += prices[i] - prices[i-1]
                }
            }
            return max
        }
        
  • 相关阅读:
    Python学习摘要201802
    机器学习-梯度下降参数调优小结
    用尽洪荒之力学习Flask源码
    Flask类的属性和方法大全
    Flask第三方工具组件介绍
    Flask自带的常用组件介绍
    Centos下部署Flask
    Python Tips阅读摘要
    web程序设计关于我们
    软工实践总结
  • 原文地址:https://www.cnblogs.com/leisurelylicht/p/122-mai-mai-gu-piao-de-zui-jia-shi-jiII.html
Copyright © 2020-2023  润新知