首页 > 试题广场 >

买卖股票的最好时机(二)

[编程题]买卖股票的最好时机(二)
  • 热度指数:42047 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
假设你有一个数组prices,长度为n,其中prices[i]是某只股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1. 你可以多次买卖该只股票,但是再次购买前必须卖出之前的股票
2. 如果不能获取收益,请返回0
3. 假设买入卖出均无手续费

数据范围:
要求:空间复杂度 ,时间复杂度
进阶:空间复杂度 ,时间复杂度
示例1

输入

[8,9,2,5,4,7,1]

输出

7

说明

在第1天(股票价格=8)买入,第2天(股票价格=9)卖出,获利9-8=1
在第3天(股票价格=2)买入,第4天(股票价格=5)卖出,获利5-2=3
在第5天(股票价格=4)买入,第6天(股票价格=7)卖出,获利7-4=3
总获利1+3+3=7,返回7        
示例2

输入

[5,4,3,2,1]

输出

0

说明

由于每天股票都在跌,因此不进行任何交易最优。最大收益为0。            
示例3

输入

[1,2,3,4,5]

输出

4

说明

第一天买进,最后一天卖出最优。中间的当天买进当天卖出不影响最终结果。最大收益为4。                

备注:
总天数不大于200000。保证股票每一天的价格在[1,100]范围内。
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        # write code here
        profile = [0]*len(prices)
        sum = 0
        for i in range(1, len(prices)):
            profile[i] = prices[i] - prices[i-1]
        for i in range(len(profile)):
            if profile[i] > 0:
                sum += profile[i]
        return sum
发表于 2023-08-16 17:06:30 回复(0)
我怎么觉得这一题比第一部分还要简单
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        if len(prices)>= 1:
            a = [0]*len(prices)
            for i in range(1,len(prices)):
                a[i] = max(prices[i]-prices[i-1],0)
            return sum(a)
        else:
            return 0


发表于 2023-03-17 00:26:09 回复(0)
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        # 定义dp[i][j]为第i天结束的时候,手上持股状态为j时,手上的现金数
        m = len(prices)
        dp = [[0 for _ in range(2)] for _ in range(m+1)]
        for i in range(1, m+1):
            if i == 1:
                dp[i][0] = dp[i-1][0]
                dp[i][1] = -prices[i-1]
            else:
                dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i-1])
                dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i-1])

        return dp[m][0]

发表于 2023-03-03 14:37:10 回复(0)
需要毛的动态规划啊。直接遍历求解
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        # write code here
        n = len(prices)
        if n < 2:
            return 0
        
        res = 0
        i = 0
        while i < n-1:
            if prices[i+1] > prices[i]:
                res += prices[i+1] - prices[i]
                i += 1
            else:
                i += 1
        return res

发表于 2022-12-04 16:54:58 回复(0)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 计算最大收益
# @param prices int整型一维数组 股票每一天的价格
# @return int整型
#
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        ret = 0
        i = 0
        while i < len(prices) - 1:
            if prices[i] < prices[i+1]:
                ret += prices[i+1] - prices[i]
            i += 1
        return ret

发表于 2022-10-01 23:59:58 回复(0)