-
Notifications
You must be signed in to change notification settings - Fork 0
/
truck-tour.php
51 lines (39 loc) · 1.08 KB
/
truck-tour.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/*
* Complete the 'truckTour' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY petrolpumps as parameter.
*/
function truckTour($petrolpumps)
{
$count = count($petrolpumps);
for ($x = 0; $x < $count;) {
$gas = 0;
$result = true;
$counter = 0;
for ($y = $x; $y < $count + $x; $y++) {
$counter++;
$realY = $y >= $count ? $y - $count : $y;
$gas += $petrolpumps[$realY][0] - $petrolpumps[$realY][1];
if ($gas < 0) {
$result = false;
break;
}
}
if ($result) {
return $x;
}
$x += $counter;
}
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$n = intval(trim(fgets(STDIN)));
$petrolpumps = array();
for ($i = 0; $i < $n; $i++) {
$petrolpumps_temp = rtrim(fgets(STDIN));
$petrolpumps[] = array_map('intval', preg_split('/ /', $petrolpumps_temp, -1, PREG_SPLIT_NO_EMPTY));
}
$result = truckTour($petrolpumps);
fwrite($fptr, $result . "\n");
fclose($fptr);