3016. Minimum Number of Pushes to Type Word II #242
-
Topics : You are given a string Telephone keypads have keys mapped with distinct collections of lowercase English letters, which can be used to form words by pushing them. For example, the key It is allowed to remap the keys numbered Return the minimum number of pushes needed to type An example mapping of letters to keys on a telephone keypad is given below. Note that Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Step-by-Step Implementation in PHP
Let's implement this solution in PHP: 3016. Minimum Number of Pushes to Type Word II <?php
function minimumPushes($word) {
// Step 1: Count the frequency of each character
$frequency = array();
for ($i = 0; $i < strlen($word); $i++) {
$char = $word[$i];
if (!isset($frequency[$char])) {
$frequency[$char] = 0;
}
$frequency[$char]++;
}
// Step 2: Sort the characters by frequency in descending order
arsort($frequency);
// Step 3: Assign characters to keys
$pushes = 0;
$position = 0;
foreach ($frequency as $char => $count) {
// Determine the number of pushes for the current character
$pushesForChar = (int)($position / 8) + 1;
$pushes += $pushesForChar * $count;
$position++;
}
return $pushes;
}
// Test cases
echo minimumPushes("abcde") . "\n"; // Output: 5
echo minimumPushes("xyzxyzxyzxyz") . "\n"; // Output: 12
echo minimumPushes("aabbccddeeffgghhiiiiii") . "\n"; // Output: 24
?> Explanation:
This approach ensures that the most frequent characters are assigned to the keys that require the fewest pushes, thereby minimizing the total number of pushes needed. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Step-by-Step Implementation in PHP
Count the Frequency of Each Character:
Sort the Characters by Frequency:
Assign Characters to Keys: