PHP implements two solutions to the maximum and problem of Continuous sub-arrays: array 2

Source: Internet
Author: User

PHP implements two solutions to the maximum and problem of Continuous sub-arrays: array 2

The example in this article describes two solutions for PHP to find the largest continuous sub-array and the problem. We will share this with you for your reference. The details are as follows:

Problem description

Returns the largest sum of sub-arrays.

Description:

Enter an integer array, and the array contains positive and negative numbers.
One or more consecutive integers in the array form a sub-array. Each sub-array has a sum.
Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ).

There are two solutions to the maximum number of consecutive subarrays and this problem. One is dynamic planning.

The solution is as follows:

function getMaxSubSum($arr){  $curSum = $arr[0];  $maxSum = $arr[0];  for($i = 1; $i < count($arr); $i++){    if($curSum > 0) $curSum += $arr[$i];    else $curSum = $arr[$i];    if($curSum > $maxSum) $maxSum = $curSum;  }  return $maxSum;}

Scan Method

function getMaxSubSum($arr){  $curSum = 0;  $maxSum = 0;  for($i = 0; $i < count($arr); $i++ ){    $curSum += $arr[$i];    if($curSum <= 0) $curSum = 0;    if($curSum > $maxSum) $maxSum = $curSum;  }  if($maxSum == 0){    $maxSum = $arr[0];    for($i = 1; $i < count($arr); $i++){      if($maxSum < $arr[$i] ) $maxSum = $arr[$i];    }  }  return $maxSum;}

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.