签到题-动态规划-买卖股票的最佳时机( 双指针 )

管理员
## 双指针 ```python class Solution: def maxProfit(self, prices: List[int]) -> int: # 第i天卖出, ( 0 ~ i-1 )天最便宜时买入 n = len( prices ) # j指向最便宜的天数 i指向卖出的天数 j = 0 ans = float( '-inf' ) for i in range( 1, n ): ans = max( ans, prices[ i ] - prices[ j ] ) # 是否更新j if prices[ i ] < prices[ j ]: j = i return ans > 0 and ans or 0 ``` ## 动态规划 ```python class Solution: def maxProfit(self, prices: List[int]) -> int: # 暴力:枚举买入天数i, 枚举卖出天数j, 取最大利润 # 每天的状态:持有股票 or 没有股票 # dp[ i ][ 0 ] 表示第i天没有股票 # dp[ i ][ 1 ] 表示第i天持有股票 n = len( prices ) dp = [ [ 0, 0 ] for _ in range( n ) ] dp[ 0 ][ 0 ] = 0 dp[ 0 ][ 1 ] = -prices[ 0 ] # 限制:买卖一次 for i in range( 1, n ): # 没有股票:原先就没有 or 当天卖出 dp[ i ][ 0 ] = max( dp[ i - 1 ][ 0 ], dp[ i - 1 ][ 1 ] + prices[ i ] ) # 持有股票:原先就持有 or 当天买入 dp[ i ][ 1 ] = max( dp[ i - 1 ][ 1 ], -prices[ i ] ) return dp[ n - 1 ][ 0 ] # 初始金额0 没有股票一定比持有股票利润大 ```
评论 0

发表评论 取消回复

Shift+Enter 换行  ·  Enter 发送
还没有评论,来发表第一条吧