《leetcode-php》获取最多两次交易股票的最大收益

本文介绍了一种算法,用于在给定的股票价格数组中找到最大的可能利润,允许进行两次交易。通过计算每个位置前后的最大价格差,该算法能够确定最佳的买卖时机。

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

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

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

Note: 

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

假设你有一个数组,其中第i个元素是某只股票在第i天的价格。

设计一个算法来求最大的利润。你最多可以进行两次交易。

注意:

你不能同时进行多个交易(即,你必须在再次购买之前出售之前买的股票)。

思路:就是求两次差值和最大,确定每个位置分割的差值的最大,然后再把整体的最大差值和求出来。

<?php
function maxProfit($arrPrice) {
    $num = count($arrPrice);
    //先算i之前最大的价格差
    $arrPro1 = array();
    $minPrice = $arrPrice[0];
    for ($i = 1; $i < $num; $i ++) {
        $arrPro1[$i] = max($arrPro1[$i - 1], $arrPrice[$i] - $minPrice);
        if ($minPrice > $arrPrice[$i]) {
            $minPrice = $arrPrice[$i];
        }
    }
    print json_encode($arrPro1);
    //再算i之后的最大价格差
    $arrPro2 = array();
    $maxPrice = $arrPrice[$num -1];
    for ($i = $num - 2; $i > 0; $i --) {
        $arrPro2[$i] = max($arrPro2[$i + 1], $maxPrice - $arrPrice[$i]);
        if ($maxPrice < $arrPrice[$i]) {
            $maxPrice = $arrPrice[$i];
        }
    }
    $maxProfit = 0;
    for ($i = 1; $i < $num -1; $i ++) {
        $maxProfit = max($maxProfit, $arrPro1[$i] + $arrPro2[$i]);
    }
    return $maxProfit;
}
$arrPrice = [1,2,3,4,5,6,7];
$ret = maxProfit($arrPrice);
print $ret;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值