search
Homephp教程php手册php求正负数数组中连续元素最大值示例

问题是给出数组,该数组由正负数字组成,找出该数组中连续元素组成的子数组的最大值。下面是PHP实现的示例,需要的朋友可以参考下

php实现正负数数组最大子序列,要求给出数组,,该数组由正负数字组成,找出该数组中连续元素组成的子数组的最大值。
这其实得算是个背包变种吧。

复制代码 代码如下:


$list = array(1,-3,-5,-7,8,9,-11,5);

$cur = 0;
$term = 0;
$res = 0;
$begin = 0;

foreach($list as $k => $v){
 $cur += $v;
 if($cur   $cur = 0;
  $begin = $k + 1;
 }
 if($cur > $res){
  $res = $cur;
  $term = $k;
 }
}
$max_seq = array_slice($list, $begin, ($term - $begin) + 1);

echo $res . ',';
print_r($max_seq);
//17,Array ( [0] => 8 [1] => 9 )

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools