zoukankan      html  css  js  c++  java
  • 122. 买卖股票的最佳时机 II

     

     

     

     思路:

    想到:prices中一列数字,任取一个为买入价格buy,在其右边任取一个为卖出价格sell;
    取[buy,...,sell]区间中相邻数字之差,这些差值求和为sum,则必有sell-buy = sum;

    本题中求最大收益,所以遍历prices,找到prices[i]-prices[i-1] > 0的位置作为买入点。
    此后一直遍历到prices末尾,将相邻两个元素的差加到ans中,最后得ans即为最大利润。

    代码一:
     1 class Solution(object):
     2     def maxProfit(self, prices):
     3         """
     4         :type prices: List[int]
     5         :rtype: int
     6         """
     7         i = 0
     8         ans = 0
     9         while i < len(prices) - 1:
    10             if prices[i + 1] < prices[i]:
    11                 i += 1
    12                 continue
    13             else:
    14                 buy = prices[i]
    15                 ans += prices[i + 1] - buy
    16                 i += 1
    17         return ans
    18 
    19 if __name__ == '__main__':
    20     solution = Solution()
    21     print(solution.maxProfit2([7, 1, 5, 3, 4, 6]))

    代码二:

     1 class Solution(object):
     2     def maxProfit(self, prices):
     3         """
     4         :type prices: List[int]
     5         :rtype: int
     6         """
     7         ans = 0
     8         for i in range(1, len(prices)):
     9             if prices[i] > prices[i - 1]:
    10                 ans += prices[i] - prices[i - 1]
    11         return ans
    12 
    13 if __name__ == '__main__':
    14     solution = Solution()
    15     print(solution.maxProfit([7, 1, 5, 3, 4, 6]))
    
    
    
     
  • 相关阅读:
    Mysql 安装
    网站搭建 so easy
    git 命令!!!!!!!!!!!
    git branch 管理常用命令
    Java开发环境的搭建以及使用eclipse从头一步步创建java项目
    git 放弃本地修改 强制更新
    java算法之猴子排序睡眠排序
    sql业务需求,查询每个分类下的前两n条数据
    mysql安装
    linux服务自启
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12748768.html
Copyright © 2011-2022 走看看