LeetCode股票问题:一次交易和不限次交易

一次交易:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

<?php

function maxProfit($prices)
{
    $count = count($prices);
    if ($count <= 1){
        return 0;
    }

    $minPos = 0;
    $maxPrice = 0;
    $start = 0;
    $end = 0;

    for ($i = 0; $i < $count; $i++){
        if ( $prices[$i] < $prices[$minPos] ){
            $minPos = $i;
        }else{
            $diff = $prices[$i] - $prices[$minPos];
            if ($maxPrice < $diff){
                $start = $minPos;
                $end = $i;
                $maxPrice = $diff;
            }
        }
    }
    return $maxPrice;
}

$prices = [7,1,5,3,6,4];
echo maxProfit($prices);

不限次交易:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

<?php

function maxProfit($prices)
{
    $count = count($prices);
    if ($count <= 1){
        return 0;
    }

    $price = 0;
    $diff = 0;
    $i = 0;
    $j = 1;
    $min_pos = 0;

    while ($j < $count){
        if ( $prices[$j] < $prices[$i] ){
            $min_pos = $j;
            if ($diff > 0){
                $price += $diff;
                $diff = 0;
            }
        }else{
            $tmp_diff = $prices[$j] - $prices[$min_pos];
            if ($tmp_diff > $diff){
                $diff = $tmp_diff;
            }
        }
        $i++;
        $j++;
    }

    //处理只涨不跌
    if ($diff > 0){
        $price += $diff;
    }
    return $price;
}
$prices = [7, 1, 5, 3, 6, 4, 5];
echo maxProfit($prices);
发布了226 篇原创文章 · 获赞 31 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/104443819
今日推荐