PHP练习-最大子序和

2020-09-10 22:14 By "Powerless" 2729 0 1

题目要求

给定一个整数数组 arr,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

function maxSubArray($arr) {
    if (!count($arr)) {
        return 0;
    }
    $dp[0] = $result = reset($arr);
    for ($i = 1; $i < count($arr); $i++) {
        $tmp = $dp[$i-1]+$arr[$i];
        $dp[$i] = $tmp > $arr[$i] ? $tmp : $arr[$i];
        $result = $dp[$i] > $result ? $dp[$i] : $result;
    }
    return $result;
}
$arr = [-2,8,-3,4,-1,2,1,-5,4];

echo maxSubArray($arr);

输出结果:11

评 论

View in WeChat

Others Discussion

  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • PHP 基金会来啦!
    Posted on 2022-10-08 17:40
  • 快速了解Kafka
    Posted on 2021-03-25 14:20
  • Redis各种数据类型的使用场景举例分析【二】
    Posted on 2018-11-22 10:30
  • TCP协议的特性
    Posted on 2019-04-26 16:46
  • 让你的PHP7更快(GCC PGO)
    Posted on 2018-03-07 14:09
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • BASE原则
    Posted on 2020-12-17 16:42