Example of continuous element maximum value in PHP _php array

Source: Internet
Author: User
PHP implements the maximum number of positive and negative arrays, which is required for the array, which consists of positive and negative numbers, to find out the maximum number of sub-arrays of contiguous elements in the array.
It's actually a backpack variant.

Copy the Code code as follows:
$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 < 0) {
$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)

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.