-
Notifications
You must be signed in to change notification settings - Fork 3
/
1103-distribute-candies-to-people.php
103 lines (90 loc) · 2.68 KB
/
1103-distribute-candies-to-people.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
// 1103. Distribute Candies to People
// https://leetcode.com/problems/distribute-candies-to-people/
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Runtime: 12 ms, faster than 100.00% of PHP online submissions
// for Distribute Candies to People.
// Memory Usage: 14.7 MB, less than 100.00% of PHP online submissions
// for Distribute Candies to People.
// class Solution
// {
// /**
// * @param Integer $candies
// * @param Integer $num_people
// * @return Integer[]
// */
// function distributeCandies($candies, $num_people)
// {
// $result = array_fill(0, $num_people, 0);
// for ($i = 1; 0 < $candies; $candies -= $i, $i++) {
// $person = ($i - 1) % $num_people;
// if ($candies < $i) {
// $result[$person] += $candies;
// break;
// }
// $result[$person] += $i;
// }
// return $result;
// }
// }
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Runtime: 12 ms, faster than 50.00% of PHP online submissions
// for Distribute Candies to People.
// Memory Usage: 14.9 MB, less than 100.00% of PHP online submissions
// for Distribute Candies to People.
class Solution
{
/**
* @param Integer $candies
* @param Integer $num_people
* @return Integer[]
*/
function distributeCandies($candies, $num_people)
{
$result = array_fill(0, $num_people, 0);
for ($i = 1; 0 < $candies; $candies -= $i++)
$result[($i - 1) % $num_people] += $candies < $i ? $candies : $i;
return $result;
}
}
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
$tests = [
[
'input' => [
'candies' => 7,
'num_people' => 4,
],
'expected' => [1, 2, 3, 1],
],
[
'input' => [
'candies' => 10,
'num_people' => 3,
],
'expected' => [5, 2, 3],
],
[
'input' => [
'candies' => 60,
'num_people' => 4,
],
'expected' => [15, 18, 15, 12],
],
];
$s = new Solution();
foreach ($tests as $test) {
extract($test);
extract($input);
$output = $s->distributeCandies($candies, $num_people);
$name = "candies = {$candies}, num_people = {$num_people}";
if ($expected === $output) {
echo "✅ ${name}<br>";
} else {
echo "🔴 ${name}<br>";
echo 'Expected the below<br>';
echo '<pre>', print_r($expected, true), '</pre>';
echo 'but got the below<br>';
echo '<pre>', print_r($output, true), '</pre>';
}
echo '<hr>';
}