• leetcode122 Best Time to Buy and Sell Stock II


     1 """
     2 Say you have an array for which the ith element is the price of a given stock on day i.
     3 Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
     4 Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
     5 Example 1:
     6 Input: [7,1,5,3,6,4]
     7 Output: 7
     8 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
     9              Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
    10 Example 2:
    11 Input: [1,2,3,4,5]
    12 Output: 4
    13 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
    14              Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
    15              engaging multiple transactions at the same time. You must sell before buying again.
    16 Example 3:
    17 Input: [7,6,4,3,1]
    18 Output: 0
    19 Explanation: In this case, no transaction is done, i.e. max profit = 0.
    20 """
    21 """
    22 搞笑的一题,容易想复杂
    23 可以与leetcode121联系来看https://www.cnblogs.com/yawenw/p/12261726.html
    24 其实这个题要求一天不能同时买和卖股票,
    25 而且必须再一笔交易完成之后才能进行下一笔交易
    26 假设序列是a <= b <= c <= d  [1, 2, 3, 4]
    27 最大利润 d - a = (b - a) + (c - b) + (d - c)
    28 假设序列是a <= b, b >= c, c <= d [1, 5, 4, 8]
    29 最大利润(b - a) + (d - b)
    30 """
    31 class Solution:
    32     def maxProfit(self, prices):
    33         res = 0
    34         for i in range(len(prices)-1):
    35             if prices[i] < prices[i+1]:
    36                 res += prices[i+1]-prices[i]
    37         return res
  • 相关阅读:
    JS解析XML文件和XML字符串
    查询优化的方法
    Oracle 常用操作
    取得同一网段内的IP和MAC地址!
    域名知多少?
    Oracle 数据库链路 同义词
    提高查询速度的方法【百万级以上数据】
    ExtJs学习之路从Grid中得到数据
    一个左边停靠且可以展开和隐藏的菜单【Jquery插件】
    Go流程控制
  • 原文地址:https://www.cnblogs.com/yawenw/p/12375441.html
Copyright © 2020-2023  润新知