Home Backend Development PHP Tutorial Maximum Number of Integers to Choose From a Range I

Maximum Number of Integers to Choose From a Range I

Dec 21, 2024 am 02:01 AM

Maximum Number of Integers to Choose From a Range I

2554. Maximum Number of Integers to Choose From a Range I

Difficulty: Medium

Topics: Array, Hash Table, Binary Search, Greedy, Sorting

You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules:

  • The chosen integers have to be in the range [1, n].
  • Each integer can be chosen at most once.
  • The chosen integers should not be in the array banned.
  • The sum of the chosen integers should not exceed maxSum.

Return the maximum number of integers you can choose following the mentioned rules.

Example 1:

  • Input: banned = [1,6,5], n = 5, maxSum = 6
  • Output: 2
  • Explanation: You can choose the integers 2 and 4.
    • 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum.

Example 2:

  • Input: banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1
  • Output: 0
  • Explanation: You cannot choose any integer while following the mentioned conditions.

Example 3:

  • Input: banned = [11], n = 7, maxSum = 50
  • Output: 7
  • Explanation: You can choose the integers 1, 2, 3, 4, 5, 6, and 7.
    • They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum.

Constraints:

  • 1 <= banned.length <= 104
  • 1 <= banned[i], n <= 104
  • 1 <= maxSum <= 109

Hint:

  1. Keep the banned numbers that are less than n in a set.
  2. Loop over the numbers from 1 to n and if the number is not banned, use it.
  3. Keep adding numbers while they are not banned, and their sum is less than k.

Solution:

We can use a greedy approach where we iterate over the numbers from 1 to n, skipping the banned numbers, and keep adding the valid numbers (those not in the banned array) to a running sum until we reach the maxSum.

Here's the step-by-step solution:

Steps:

  1. Convert banned array to a set for quick lookups: Using array_flip() can convert the banned array into a set for O(1) average-time complexity lookups.
  2. Iterate from 1 to n: Check each number, if it's not in the banned set and if adding it doesn't exceed maxSum, add it to the sum and increase the count.
  3. Stop once adding the next number exceeds maxSum: Since the goal is to maximize the number of chosen integers without exceeding the sum, this greedy approach ensures we take the smallest available numbers first.

Approach:

  1. Exclude Banned Numbers: We'll keep track of the banned numbers in a set (or an associative array) for fast lookups.
  2. Greedy Selection: Start selecting numbers from 1 to n in ascending order, as this will allow us to maximize the number of integers selected. Each time we select a number, we'll add it to the sum and check if it exceeds maxSum. If it does, stop.
  3. Efficiency Considerations: Since we are iterating over numbers from 1 to n, and checking if each is in the banned set (which can be done in constant time), the approach runs in linear time relative to n and the size of the banned list.

Let's implement this solution in PHP: 2554. Maximum Number of Integers to Choose From a Range I

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

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

<!--?php

/**

 * @param Integer[] $banned

 * @param Integer $n

 * @param Integer $maxSum

 * @return Integer

 */

function maxCount($banned, $n, $maxSum) {

    ...

    ...

    ...

    /**

     * go to ./solution.php

     */

}

 

// 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

?-->

 

 

 

 

<h3>

   

   

  Explanation:

</h3>

 

<ol>

<li><p><strong>Convert banned array to set:</strong><br><br>

We use array_flip($banned) to create a set from the banned array, which allows for O(1) lookups to check if a number is banned.</p></li>

<li>

<p><strong>Iterate from 1 to n:</strong><br><br>

We iterate through numbers from 1 to n. For each number:</p>

 

<ul>

<li>If the number is not in the banned set (checked using isset($bannedSet[$i])),</li>

<li>And if adding the number to the sum does not exceed maxSum,</li>

<li>We include that number and update the sum and count.</li>

</ul>

</li>

<li><p><strong>Return the count:</strong><br><br>

After the loop, we return the number of integers selected ($count).</p></li>

<li><p><strong>$bannedSet = array_flip($banned);</strong>: This converts the banned list into a set (associative array) for fast lookups.</p></li>

<li><p><strong>for ($i = 1; $i <= $n; $i  )</strong>: We iterate over all integers from 1 to n.</p></li>

<li><p><strong>if (isset($bannedSet[$i])) { continue; }</strong>: This checks if the current number is in the banned set. If it is, we skip it.</p></li>

<li><p><strong>if ($sum   $i > $maxSum) { break; }</strong>: If adding the current number exceeds maxSum, we stop the process.</p></li>

<li><p><strong>$sum  = $i; $count  ;</strong>: If the number is valid and adding it doesn't exceed maxSum, we include it in our sum and increase the count.</p></li>

</ol>

 

<h3>

   

   

  Time Complexity:

</h3>

 

<ul>

<li>The creation of the banned set (array_flip) is O(b), where b is the length of the banned array.</li>

<li>The loop iterates n times (for numbers from 1 to n), and each lookup into the banned set takes O(1) time. So, the time complexity of the loop is O(n).</li>

<li>Thus, the overall time complexity is O(n   b), which is efficient given the problem constraints.</li>

</ul>

 

<h3>

   

   

  Example Walkthrough:

</h3>

 

<p>For the input:</p>

 

<ul>

<li>

<p><strong>Input 1:</strong> banned = [1, 6, 5], n = 5, maxSum = 6</p>

 

<ul>

<li>We create the banned set: {1, 5, 6}.</li>

<li>We iterate through numbers 1 to 5:

 

<ul>

<li>1 is banned, skip it.</li>

<li>2 is not banned, add it to sum (sum = 2, count = 1).</li>

<li>3 is not banned, add it to sum (sum = 5, count = 2).</li>

<li>4 is not banned, but adding it to the sum would exceed maxSum (5   4 = 9), so skip it.</li>

</ul>

 

 

</li>

 

<li>The result is 2.</li>

 

</ul>

 

</li>

 

<li>

 

<p><strong>Input 2:</strong> banned = [1, 2, 3, 4, 5, 6, 7], n = 8, maxSum = 1</p>

 

<ul>

<li>All numbers from 1 to 7 are banned, so no valid numbers can be chosen.</li>

<li>The result is 0.</li>

</ul>

 

 

</li>

 

<li>

 

<p><strong>Input 3:</strong> banned = [11], n = 7, maxSum = 50</p>

 

<ul>

<li>The only banned number is 11, which is outside the range 1 to 7.</li>

<li>We can select all numbers from 1 to 7, and their sum is 28, which is less than maxSum.</li>

<li>The result is 7.</li>

</ul>

 

 

</li>

 

</ul>

 

<p>This solution efficiently handles the problem within the given constraints.</p>

 

<p><strong>Contact Links</strong></p>

 

<p>If you found this series helpful, please consider giving the <strong>repository</strong> a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!</p>

 

<p>If you want more helpful content like this, feel free to follow me:</p>

 

<ul>

<li><strong>LinkedIn</strong></li>

<li><strong>GitHub</strong></li>

</ul>

 

 

           

 

             

   

 

             

         

<p>The above is the detailed content of Maximum Number of Integers to Choose From a Range I. For more information, please follow other related articles on the PHP Chinese website!</p>

 

 

                        

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles