1、题目
给你一个整数数组
prices
,其中prices[i]
表示某支股票第i
天的价格。在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。返回 你能获得的 最大利润 。
2、题解
3、代码
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# tfjiao解决思路
# a = []
# for i in range(len(prices)-1):
# if prices[i+1] > prices[i]:
# a.append(prices[i+1]-prices[i])
# return sum(a)
# 列表推导式优化后的
return sum([prices[i+1]-prices[i] for i in range(len(prices)-1) if prices[i+1] > prices[i]])
# zip()
li = []
for a,b in zip(prices, prices[1:]):
if b > a:
li.append(b-a)
return sum(li)
if __name__ == '__main__':
a = [7,1,5,3,6,4]
so = Solution()
print(so.maxProfit(a))
4、zip()函数解读
4.1 基本概念
zip(*iterables, strict=False)
:在多个迭代器上并行迭代,从每个迭代器返回一个数据项组成元组,zip()返回的是元组的迭代器,其中第n个元组好汉的是每个参数迭代器的第n个元素,是延迟执行的,直到迭代时才会对元素进行处理,比如for循环中
for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
print(item)
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
- 默认情况下,zip()在最短的迭代完成后停止,较长可迭代对象中的剩余项将被自动忽略
>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
[(0, 'fee'), (1, 'fi'), (2, 'fo')]
- Python 3.10 版本新增strict参数,当 strict=True 后,它会检查可迭代对象的长度是否相同,不同则出发异常 ValueError
list(zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True))
Traceback (most recent call last):
...
ValueError: zip() argument 2 is longer than argument 1
如果未指定 strict=True 参数,所有导致可迭代对象长度不同的错误都会被抑制
>>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))
[('a', 1), ('b', 2), ('c', 3)]
4.2 小技巧
1、可确保迭代器的求值顺序是从左到右的。
2、拆解列表
3、迭代取值