2554. Maximum Number of Integers to Choose From a Range I #920
-
Topics: You are given an integer array
Return the maximum number of integers you can choose following the mentioned rules. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a greedy approach where we iterate over the numbers from Here's the step-by-step solution: Steps:
Approach:
Let's implement this solution in PHP: 2554. Maximum Number of Integers to Choose From a Range I <?php
/**
* @param Integer[] $banned
* @param Integer $n
* @param Integer $maxSum
* @return Integer
*/
function maxCount($banned, $n, $maxSum) {
// Convert banned array to a set for O(1) lookup
$bannedSet = array_flip($banned);
$sum = 0; // Initialize the running sum
$count = 0; // Initialize the count of numbers we can select
// Loop through numbers from 1 to n
for ($i = 1; $i <= $n; $i++) {
// Skip numbers that are in the banned set
if (isset($bannedSet[$i])) {
continue;
}
// Check if adding this number exceeds maxSum
if ($sum + $i > $maxSum) {
break;
}
// Add this number to the sum and increment the count
$sum += $i;
$count++;
}
return $count;
}
// Test cases
echo maxCount([1, 6, 5], 5, 6); // Output: 2
echo "\n";
echo maxCount([1, 2, 3, 4, 5, 6, 7], 8, 1); // Output: 0
echo "\n";
echo maxCount([11], 7, 50); // Output: 7
?> Explanation:
Time Complexity:
Example Walkthrough:For the input:
This solution efficiently handles the problem within the given constraints. |
Beta Was this translation helpful? Give feedback.
We can use a greedy approach where we iterate over the numbers from
1
ton
, skipping the banned numbers, and keep adding the valid numbers (those not in thebanned
array) to a running sum until we reach themaxSum
.Here's the step-by-step solution:
Steps:
array_flip()
can convert thebanned
array into a set for O(1) average-time complexity lookups.maxSum
, add it to the sum and increase the count.maxSum
: Since the goal is to maximize the number of chosen integers without exceeding the sum, th…