《leetcode-php》求一组股票趋势的最高收益

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, 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);
    //不能满足基本的两次买卖
    if ($num < 2) {
        return 0;
    }
    //先算i之前最大的价格差
    $min       = $arrPrice[0];
    $isAdd     = 0;
    $isSub     = 0;
    $maxProfit = 0;
    for ($idx = 1; $idx < $num; $idx ++) {
        if ($arrPrice[$idx] > $arrPrice[$idx - 1] ) {
            //递减的结束位置
            if ($isSub == 1) {
                $min = $arrPrice[$idx - 1];
            }
            //单增的情况
            if ($idx == $num - 1) {
                $maxProfit += $arrPrice[$idx] - $min;
            }
            $isAdd = 1;//标志递增
            $isSub = 0;//标记递减
        }
        if ($arrPrice[$idx] < $arrPrice[$idx - 1]) {
            //递增结束的位置
            if ($isAdd == 1) {
                $maxProfit += $arrPrice[$idx - 1] - $min;
            }
            $isAdd = 0;//标志递增
            $isSub = 1;//标记递减
        }
        print $idx. ' ' . $maxProfit . ' ' . $arrPrice[$idx] . "\n";
    }
    return $maxProfit;
}
$arrPrice = [1,2,3,4,5,6,7];
//$arrPrice = array(1,2,3,4,5,4,7);
$ret = maxProfit($arrPrice);
print $ret;

其实上面的比较麻烦,虽然题目限制了一天不能同时交易,但是我们可以直接把所有递增的收益求出来,就不用记录哪里到哪里是递增了。

<?php
function maxProfit($arrPrice) {
    $num = count($arrPrice);
    $maxProfit = 0;
    for ($i = 1; $i <$num; $i ++) {
        if ($arrPrice[$i] > $arrPrice[$i - 1]) {
            $maxProfit += $arrPrice[$i] - $arrPrice[$i - 1];
        }
    }
    return $maxProfit;
}
$arrPrice = [1,2,3,4,5,6,7,1,2,3];
//$arrPrice = array(1,2,3,4,5,4,7);
$ret = maxProfit($arrPrice);
print $ret;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值