Find maximum difference between two elements
EASY
Given a string of numbers separated by a single space.
Find the maximum difference between two elements in the string such that smaller element appears after the larger element.
For example, answer for string "1 6 4 3" is: "3" (6-3)
Solution
<?php
$line = trim(fgets(STDIN));
$nums = explode(' ', $line);
$numsCount = count($nums);
$maxDiff = null;
foreach ($nums as $i => $num1) {
for ($j = $i + 1; $j < $numsCount; $j++) {
$num2 = $nums[$j];
if ($num1 <= $num2) {
continue;
}
if ($maxDiff === null) {
$maxDiff = $num1 - $num2;
continue;
}
$maxDiff = max($maxDiff, $num1 - $num2);
}
}
echo $maxDiff;
Tests
Test #1 |
Loading...
|
Test #2 |
Loading...
|
Test #3 |
Loading...
|
Test #4 |
Loading...
|