Best Time to Buy and Sell Stock

文章介绍了如何使用双指针算法解决股票买卖问题,通过遍历数组计算每次买入后卖出的最大利润,最终返回总的最大利润。算法具有O(n)的时间复杂度和O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Intuition

The problem asks for the maximum profit that can be achieved by buying and selling a stock. The idea is to find the optimal days to buy and sell to maximize the profit. If it is not possible to make a profit, the function should return 0.

Approach

The provided solution uses a two-pointer approach to iterate through the array and find the maximum profit.

Initialize two pointers, left and right, to represent the buying and selling days, respectively.
Initialize a variable maxp to keep track of the maximum profit.
While the right pointer is not at the end of the array:
Calculate the profit by subtracting the price on the buying day (prices[left]) from the price on the selling day (prices[right]).
Update maxp with the maximum of its current value and the calculated profit.
If the profit is greater than 0, move the right pointer to the next day.
If the profit is not greater than 0, reset the pointers to the current day and move them to the next day.
Return the maximum profit.

Complexity

  • Time complexity:

The time complexity of this solution is O(n), where n is the length of the input array prices. The two-pointer approach allows for a single pass through the array.

  • Space complexity:

The space complexity is O(1), as the solution uses only a constant amount of space to store pointers and variables.

Code

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        left,right = 0 , 1
        maxp = 0
        while right != len(prices):
            profit = prices[right] - prices[left]
            maxp = max(maxp,profit)
            if profit > 0:
                right+=1
            else:
                left = right
                right+=1
        return maxp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值