Say you have an array for which the ith element is the price of a given stock on day i.

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).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

原题地址: Best Time to Buy and Sell Stock II

难度: Easy

题意: 买卖股票,允许多次买卖,但不允许同一天即买入又卖出,返回最大利润

思路:

遍历数组, 计算当前一个数与前一个数的差值, 差值大于0,表明是利润

代码:

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
res = 0 for i in range(1, n):
profit = prices[i] - prices[i-1]
if profit > 0:
res += profit
return res

时间复杂度: O(n)

空间复杂度: O(1)

最新文章

  1. STOP:c0000218 {Registry File Failure}
  2. Spring强制使用CGLIB代理事务
  3. index 辨别字符在字符串中的位置
  4. 如何编译POCO
  5. jquery和javascript的区别(常用方法比较)
  6. 关于前后端同构,我的一点思路和心得(vue、nodejs、react、模版、amd)
  7. Storm集群安装与部署
  8. 【46】java对象的三个特征(oop)
  9. QT5:C++实现基于multimedia的音乐播放器(二)
  10. xml的作用
  11. Spark-RPC理解
  12. mybatis,mysql批量delete多个记录
  13. OnCheckedChangeListener和setChecked之间冲突问题解决
  14. 使用ssm(spring+springMVC+mybatis)创建一个简单的查询实例(二)(代码篇)
  15. Spring Cloud(Dalston.SR5)--Eureka 注册中心搭建
  16. HTML 列表实例
  17. 【转】windows平台多线程同步之Mutex的应用
  18. angularjs-$location
  19. vue 使用ref获取DOM元素和组件引用
  20. STL Deque 容器

热门文章

  1. bzoj 4472: [Jsoi2015]salesman【树形dp+贪心】
  2. AtCoder Grand Contest 003 F - Fraction of Fractal
  3. UvaLive6442(思维、结论)
  4. Educational Codeforces Round 20 B
  5. 组合数+容斥原理 UVALive 7040 Color(14西安F)
  6. 什么是极坐标? —— 一点微小的想法 What is Polar Coordinate ? - Some Naive Thoughts about It
  7. state vs props
  8. canvas防画图工具
  9. Design Compiler 综合
  10. 在colab上运行style-transfer