Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 20eedcd

Browse files
committed
Add solution for Minimum Operations to Make Array Values Equal to K
1 parent 9851051 commit 20eedcd

File tree

1 file changed

+55
-0
lines changed
  • Easy/3375. Minimum Operations to Make Array Values Equal to K

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
class Solution
3+
{
4+
/**
5+
* @param Integer[] $nums
6+
* @param Integer $k
7+
* @return Integer
8+
*/public function minOperations(array $nums, int $k): int
9+
{
10+
$freq = [];
11+
$nonK = 0;
12+
13+
// Count all numbers ≠ k
14+
foreach ($nums as $num) {
15+
if ($num != $k) {
16+
$freq[$num] = ($freq[$num] ?? 0) + 1;
17+
$nonK++;
18+
}
19+
}
20+
21+
$pairs = 0;
22+
23+
foreach ($freq as $num => $count) {
24+
$target = 2 * $k - $num;
25+
26+
if (isset($freq[$target])) {
27+
if ($num == $target) {
28+
// Use pairs within the same value
29+
$pairCount = intdiv($freq[$num], 2);
30+
$pairs += $pairCount;
31+
$freq[$num] -= $pairCount * 2;
32+
} elseif ($num < $target) {
33+
// Pair num with target
34+
$pairCount = min($freq[$num], $freq[$target]);
35+
$pairs += $pairCount;
36+
$freq[$num] -= $pairCount;
37+
$freq[$target] -= $pairCount;
38+
}
39+
}
40+
}
41+
42+
// After using valid pairs, each of the remaining non-k elements needs 1 op
43+
return $nonK - $pairs * 2;
44+
}
45+
}
46+
47+
$solution = new Solution();
48+
49+
$nums = [1, 2, 3, 4, 5]; // Example input array
50+
51+
$k = 3; // Example target value
52+
53+
$result = $solution->minOperations($nums, $k); // Call the function with the example input
54+
55+
echo $result; // Output: 4 (Explanation: The minimum number of operations required to make all elements equal to 3 is 4)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /