Maximum sum in sequence
MEDIUM
Given a string of integers separated by a single space.
Find a sequence of numbers in which the sum of the elements is maximum.
For example, for string "2, -5, 1, 2, -2, 2" solution is the sequence "1 2" with sum = 3.
Print max sum only.
Solution
<?php
$line = trim(fgets(STDIN));
$nums = explode(' ', $line);
$numsCount = count($nums);
$maxSumCurrent = $nums[0];
$maxSumTotal = $nums[0];
for ($i = 1; $i < $numsCount; $i++) {
$num = $nums[$i];
$maxSumCurrent += $num;
if ($maxSumCurrent < $num) {
$maxSumCurrent = $num;
}
if ($maxSumCurrent > $maxSumTotal) {
$maxSumTotal = $maxSumCurrent;
}
}
echo $maxSumTotal;
Tests
| Test #1 |
Loading...
|
| Test #2 |
Loading...
|
| Test #3 |
Loading...
|
| Test #4 |
Loading...
|