DP (二): LeetCode123. Best Time to Buy and Sell Stock III

本文介绍了解决LeetCode123题目的高效算法,目标是在给定股票价格数组中找到最大利润,允许进行最多两次交易。通过寻找两对极小极大值并求其差值总和的最大值,提出了一种O(n)复杂度的解决方案。

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

LeetCode123. Best Time to Buy and Sell Stock III

题目

Say you have an array for which the i i ith element is the price of a given stock on day i i i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

思路

原题目等价于找到两对极小极大值, 使得他们之差的总和最大.
最优解法只需要 O(n) 的复杂度, 逻辑… 有点难讲, 先占坑日后一定会回来填!!

代码 ( C语言, 复杂度 O(n) )

int max(int a, int b) {
    return (a > b) ? a : b;
}

int maxProfit(int* prices, int pricesSize){
    int before1 = 0x80000000;
    int before2 = 0x80000000;
    int after1 = 0;
    int after2 = 0;
    for (int i = 0; i < pricesSize; i++) {
        before1 = max(before1, 0-prices[i]);
        after1 = max(after1, before1+prices[i]);
        before2 = max(before2, after1-prices[i]);
        after2 = max(after2, before2+prices[i]);
    }
    return after2;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值