2034.股票价格波动
from sortedcontainers import SortedList
class StockPrice(object):
def __init__(self):
#有序集合,维护哈希表中的价格
self.price = SortedList()
#哈希表,记录每个时间戳对应的股价
self.timePriceMap = {}
#维护最大时间戳,获取最新股价
self.maxTimestamp = 0
def update(self, timestamp, price):
"""
:type timestamp: int
:type price: int
:rtype: None
"""
#时间戳重复,需删除原先的股价
if timestamp in self.timePriceMap:
self.price.discard(self.timePriceMap[timestamp])
#更新有序集合中的股价,并更新哈希表
self.price.add(price)
self.timePriceMap[timestamp] = price
#更新最大时间戳,以便获取最新股价
self.maxTimestamp = max(self.maxTimestamp,timestamp)
def current(self):
"""
:rtype: int
"""
return self.timePriceMap[self.maxTimestamp]
def maximum(self):
"""
:rtype: int
"""
return self.price[-1]
def minimum(self):
"""
:rtype: int
"""
return self.price[0]
901.股票价格跨度
from sortedcontainers import SortedList
class StockPrice(object):
def __init__(self):
#有序集合,维护哈希表中的价格
self.price = SortedList()
#哈希表,记录每个时间戳对应的股价
self.timePriceMap = {}
#维护最大时间戳,获取最新股价
self.maxTimestamp = 0
def update(self, timestamp, price):
"""
:type timestamp: int
:type price: int
:rtype: None
"""
#时间戳重复,需删除原先的股价
if timestamp in self.timePriceMap:
self.price.discard(self.timePriceMap[timestamp])
#更新有序集合中的股价,并更新哈希表
self.price.add(price)
self.timePriceMap[timestamp] = price
#更新最大时间戳,以便获取最新股价
self.maxTimestamp = max(self.maxTimestamp,timestamp)
def current(self):
"""
:rtype: int
"""
return self.timePriceMap[self.maxTimestamp]
def maximum(self):
"""
:rtype: int
"""
return self.price[-1]
def minimum(self):
"""
:rtype: int
"""
return self.price[0]
# Your StockPrice object will be instantiated and called as such:
# obj = StockPrice()
# obj.update(timestamp,price)
# param_2 = obj.current()
# param_3 = obj.maximum()
# param_4 = obj.minimum()
714. 买卖股票的最佳时机含手续费
class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
n = len(prices)
# dp = [[0,-prices[0]]] + [[0,0] for _ in range(n-1)]
# for i in range(1,n):
# dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i] - fee)
# dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
# return dp[n-1][0]
#只关心结果的dp[n-1][0],所以无需存储全部数组
sold, buy = 0, -prices[0]
for i in range(1,n):
sold, buy = max(sold,buy + prices[i] - fee), max(sold - prices[i],buy)
return sold