Example of the maximum number of consecutive elements in a PHP-positive array

Source: Internet
Author: User

The problem is to give the array, which is composed of positive and negative digits, to find the maximum value of the substring of contiguous elements in the array. The following is an example of the implementation of PHP, you need friends can refer to the following

PHP implementation of the maximum number of positive and negative array of sub-sequence, the array of numbers, which consists of positive and negative digits, to find the array of contiguous elements of the maximum size of the child array.   It's actually a backpack variant.   The code is as follows: <?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 < 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.