Open In App

Maximum number of people that can be killed with strength P

Last Updated : 02 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

There are infinite people standing in a row, indexed from 1. A person having index i has strength of i2. You have strength P and the task is to tell what is the maximum number of people you can kill with strength P
You can only kill a person with strength X if P ? X and after killing him, your strength decreases by X

Examples: 

Input: P = 14 
Output:
Explanation: First person will have strength 12 = 1 which is < P 
P gets reduced to 13 after the first kill. 
Second kill, P = 13 – 22 = 9 
Third kill, P = 9 – 32 = 0

Input: P = 58 
Output:

Naive approach: Check every single kill starting from 1 until the strength P is greater than or equal to the strength of the person being killed.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximum number of people that can
// be killed
int maxPeople(int p)
{
    int tmp = 0, count = 0;
 
    // Loop will break when the ith person cannot be killed
    for (int i = 1; i * i <= p; i++) {
        tmp = tmp + (i * i);
        if (tmp <= p)
            count++;
        else
            break;
    }
    return count;
}
 
// Driver code
int main()
{
    int p = 14;
    cout << maxPeople(p);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C implementation of the approach
#include <stdio.h>
 
// Function to return the maximum number of people that can
// be killed
int maxPeople(int p)
{
    int tmp = 0, count = 0;
 
    // Loop will break when the ith person cannot be killed
    for (int i = 1; i * i <= p; i++) {
        tmp = tmp + (i * i);
        if (tmp <= p)
            count++;
        else
            break;
    }
    return count;
}
 
// Driver code
int main()
{
    int p = 14;
    printf("%d", maxPeople(p));
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java implementation of the approach
import java.util.*;
 
class GFG {
    // Function to return the maximum number of people that
    // can be killed
    static int maxPeople(int p)
    {
        int tmp = 0, count = 0;
 
        // Loop will break when the ith person cannot be
        // killed
        for (int i = 1; i * i <= p; i++) {
            tmp = tmp + (i * i);
            if (tmp <= p)
                count++;
            else
                break;
        }
        return count;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int p = 14;
        System.out.println(maxPeople(p));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 implementation of the approach
 
from math import sqrt
 
# Function to return the maximum
# number of people that can be killed
def maxPeople(p) :
     
    tmp = 0; count = 0;
 
    # Loop will break when the ith person
    # cannot be killed
    for i in range(1, int(sqrt(p)) + 1) :
        tmp = tmp + (i * i);
        if (tmp <= p) :
            count += 1;
        else :
            break;
     
    return count;
 
 
# Driver code
if __name__ == "__main__" :
 
    p = 14;
    print(maxPeople(p));
     
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to return the maximum
// number of people that can be killed
static int maxPeople(int p)
{
    int tmp = 0, count = 0;
 
    // Loop will break when the ith person
    // cannot be killed
    for (int i = 1; i * i <= p; i++)
    {
        tmp = tmp + (i * i);
        if (tmp <= p)
            count++;
        else
            break;
    }
    return count;
}
 
// Driver code
public static void Main()
{
    int p = 14;
    Console.WriteLine(maxPeople(p));
}
}
 
// This code is contributed by anuj_67..


Javascript




<script>
 
// javascript implementation of the approach
   
// Function to return the maximum
// number of people that can be killed
function maxPeople(p)
{
    var tmp = 0, count = 0;
 
    // Loop will break when the ith person
    // cannot be killed
    for (var i = 1; i * i <= p; i++)
    {
        tmp = tmp + (i * i);
        if (tmp <= p)
            count++;
        else
            break;
    }
    return count;
}
 
// Driver code
 
var p = 14;
document.write(maxPeople(p));
 
// This code is contributed by Amit Katiyar
 
</script>


Output

3

Time Complexity: O(sqrt(N)), where N is the initial strength.
Auxiliary Space: O(1)

Efficient approach: We can see if we kill ith person then we have already killed (i – 1)th person. This means it is a monotonic function f whose domain is the set of integers. Now we can apply binary search on this monotonic function in which instead of array lookup we are now looking for some x such that f(x) is equal to the target value. Time complexity reduces to O(Log(n)).

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
#define ll long long
 
static constexpr int kN = 1000000;
 
// Function to return the maximum
// number of people that can be killed
int maxPeople(int p)
{
    // Storing the sum beforehand so that
    // it can be used in each query
    ll sums[kN];
    sums[0] = 0;
    for (int i = 1; i < kN; i++)
        sums[i] = (ll)(i * i) + sums[i - 1];
 
    // lower_bound returns an iterator pointing to the
    // first element greater than or equal to your val
    auto it = std::lower_bound(sums, sums + kN, p);
    if (*it > p) {
 
        // Previous value
        --it;
    }
 
    // Returns the index in array upto which
    // killing is possible with strength P
    return (it - sums);
}
 
// Driver code
int main()
{
    int p = 14;
    cout << maxPeople(p);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
 
static int kN = 1000000;
 
// Function to return the maximum
// number of people that can be killed
static int maxPeople(int p)
{
    // Storing the sum beforehand so that
    // it can be used in each query
    long []sums = new long[kN];
    sums[0] = 0;
    for (int i = 1; i < kN; i++)
        sums[i] = (long)(i * i) + sums[i - 1];
 
    // lower_bound returns an iterator pointing to the
    // first element greater than or equal to your val
    int it = lower_bound(sums, 0, kN, p);
    if (sums[it] > p)
    {
 
        // Previous value
        --it;
    }
 
    // Returns the index in array upto which
    // killing is possible with strength P
    return it;
}
private static int lower_bound(long[] a, int low,
                            int high, int element)
{
    while(low < high)
    {
        int middle = low + (high - low)/2;
        if(element > a[middle])
            low = middle + 1;
        else
            high = middle;
    }
    return low;
}
 
// Driver code
public static void main(String[] args)
{
    int p = 14;
    System.out.println(maxPeople(p));
}
}
 
/* This code is contributed by PrinciRaj1992 */


Python3




# Python3 implementation of the approach
kN = 1000000;
 
# Function to return the maximum
# number of people that can be killed
def maxPeople(p):
 
    # Storing the sum beforehand so that
    # it can be used in each query
    sums = [0] * kN;
    sums[0] = 0;
    for i in range(1, kN):
        sums[i] = (i * i) + sums[i - 1];
 
    # lower_bound returns an iterator
    # pointing to the first element
    # greater than or equal to your val
    it = lower_bound(sums, 0, kN, p);
    if (it > p):
 
        # Previous value
        it -= 1;
 
    # Returns the index in array upto which
    # killing is possible with strength P
    return it;
 
def lower_bound(a, low, high, element):
    while(low < high):
        middle = int(low + (high - low) / 2);
        if(element > a[middle]):
            low = middle + 1;
        else:
            high = middle;
    return low;
 
# Driver code
if __name__ == '__main__':
    p = 14;
    print(maxPeople(p));
 
# This code contributed by Rajput-Ji


C#




// C# implementation of the approach
using System;    
     
public class GFG
{
 
static int kN = 1000000;
 
// Function to return the maximum
// number of people that can be killed
static int maxPeople(int p)
{
    // Storing the sum beforehand so that
    // it can be used in each query
    long []sums = new long[kN];
    sums[0] = 0;
    for (int i = 1; i < kN; i++)
        sums[i] = (long)(i * i) + sums[i - 1];
 
    // lower_bound returns an iterator pointing to the
    // first element greater than or equal to your val
    int it = lower_bound(sums, 0, kN, p);
    if (it > p)
    {
 
        // Previous value
        --it;
    }
 
    // Returns the index in array upto which
    // killing is possible with strength P
    return it;
}
private static int lower_bound(long[] a, int low,
                            int high, int element)
{
    while(low < high)
    {
        int middle = low + (high - low)/2;
        if(element > a[middle])
            low = middle + 1;
        else
            high = middle;
    }
    return low;
}
 
// Driver code
public static void Main(String[] args)
{
    int p = 14;
    Console.WriteLine(maxPeople(p));
}
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
// Javascript implementation of the approach
 
const kN = 1000000;
 
// Function to return the maximum
// number of people that can be killed
function maxPeople(p)
{
    // Storing the sum beforehand so that
    // it can be used in each query
    let sums = new Array(kN);
    sums[0] = 0;
    for (let i = 1; i < kN; i++)
        sums[i] = (i * i) + sums[i - 1];
 
    // lower_bound returns an iterator pointing to the
    // first element greater than or equal to your val
    let it = lower_bound(sums, 0, kN, p);
    if (it > p) {
 
        // Previous value
        --it;
    }
 
    // Returns the index in array upto which
    // killing is possible with strength P
    return it;
}
 
function lower_bound(a, low, high, element)
{
    while(low < high)
    {
        let middle = low + parseInt((high - low)/2);
        if(element > a[middle])
            low = middle + 1;
        else
            high = middle;
    }
    return low;
}
 
// Driver code
    let p = 14;
    document.write(maxPeople(p));
 
</script>


Output

3

Time Complexity: O(1000000)

Auxiliary Space: O(1000000)

More Efficient Approach : 
We can do the same problem in time complexity O(logn) and Space Complexity in O(1). Start your binary search by considering the value of low as 0 and high as 10^15. We will calculate the mid-value and according to mid, we will change the position of low and high. 

Below is the implementation of the above approach. 

C++




// C++ implementation of the approach
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
     
// Helper function which returns the sum
// of series (1^2 + 2^2 +...+ n^2)
long squareSeries(long n)
{
    return(n * (n + 1) * (2 * n + 1)) / 6;
}
 
// maxPeople function which returns
// appropriate value using Binary Search
// in O(logn)
long maxPeople(long n)
{
     
    // Set the lower and higher values
    long low = 0;
    long high = 1000000L;
    long ans = 0L;
     
    while (low <= high)
    {
         
        // Calculate the mid using
        // low and high
        long mid = low + ((high - low) / 2);
        long value = squareSeries(mid);
 
        // Compare value with n
        if (value <= n)
        {
            ans = mid;
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
     
    // Return the ans
    return ans;
}
 
// Driver code
int main()
{
    long p = 14;
     
    cout<<maxPeople(p);
    return 0;
}
 
 
// This code contributed by shikhasingrajput


Java




// Java implementation of the approach
class GFG{
     
// Helper function which returns the sum
// of series (1^2 + 2^2 +...+ n^2)
static long squareSeries(long n)
{
    return(n * (n + 1) * (2 * n + 1)) / 6;
}
 
// maxPeople function which returns
// appropriate value using Binary Search
// in O(logn)
static long maxPeople(long n)
{
     
    // Set the lower and higher values
    long low = 0;
    long high = 1000000L;
    long ans = 0L;
     
    while (low <= high)
    {
         
        // Calculate the mid using
        // low and high
        long mid = low + ((high - low) / 2);
        long value = squareSeries(mid);
 
        // Compare value with n
        if (value <= n)
        {
            ans = mid;
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
     
    // Return the ans
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    long p = 14;
     
    System.out.println(maxPeople(p));
}}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of the approach
 
# helper function which returns the sum
# of series (1^2 + 2^2 +...+ n^2)
def squareSeries(n):
    return (n*(n+1)*(2*n+1))//6
 
# maxPeople function which returns
# appropriate value using Binary Search
# in O(logn)
 
def maxPeople(n):
 
    # Set the lower and higher values
    low = 0
    high = 1000000000000000
    while low<=high:
 
        # calculate the mid using
        # low and high
 
        mid = low + ((high-low)//2)
        value = squareSeries(mid)
 
        #compare value with n
        if value<=n:
            ans = mid
            low = mid+1
        else:
            high = mid-1
 
    # return the ans
    return ans
 
if __name__=='__main__':
    p=14
    print(maxPeople(p))
 
# This code is contributed bu chaudhary_19
# (* Mayank Chaudhary)


C#




// C# implementation of the approach
using System;
 
class GFG{
     
// Helper function which returns the sum
// of series (1^2 + 2^2 +...+ n^2)
static long squareSeries(long n)
{
    return(n * (n + 1) * (2 * n + 1)) / 6;
}
 
// maxPeople function which returns
// appropriate value using Binary Search
// in O(logn)
static long maxPeople(long n)
{
     
    // Set the lower and higher values
    long low = 0;
    long high = 1000000L;
    long ans = 0L;
     
    while (low <= high)
    {
         
        // Calculate the mid using
        // low and high
        long mid = low + ((high - low) / 2);
        long value = squareSeries(mid);
 
        // Compare value with n
        if (value <= n)
        {
            ans = mid;
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
     
    // Return the ans
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    long p = 14;
     
    Console.Write(maxPeople(p));
}}
 
// This code is contributed by shivanisinghss2110


Javascript




<script>
// Javascript implementation of the approach
 
// Helper function which returns the sum
// of series (1^2 + 2^2 +...+ n^2)
function squareSeries(n)
{
    return Math.floor((n * (n + 1) * (2 * n + 1)) / 6);
}
 
// maxPeople function which returns
// appropriate value using Binary Search
// in O(logn)
function maxPeople(n)
{
 
    // Set the lower and higher values
    let low = 0;
    let high = 1000000;
    let ans = 0;
      
    while (low <= high)
    {
          
        // Calculate the mid using
        // low and high
        let mid = low + Math.floor((high - low) / 2);
        let value = squareSeries(mid);
  
        // Compare value with n
        if (value <= n)
        {
            ans = mid;
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
      
    // Return the ans
    return ans;
}
 
// Driver code
let p = 14;
 
document.write(maxPeople(p));
 
// This code is contributed by avanitrachhadiya2155
</script>


Output

3

Time Complexity: O(Log(1000000)) 
Auxiliary Space: O(1)
 



Similar Reads

Count arrangements of N people around circular table such that K people always sit together
Given integers N and K, the task is to find the number of possible arrangements of N people around a circular table such that K people always sit together. Note: As the answer can be very large return it modulo 109 + 7 Examples: Input: N = 4, K = 3Output: 6Explanation: If 3 people always sit together (say 1, 2 and 3) then the possible arrangements
5 min read
Find maximum number of people who can attend meeting
There is only one room which is holding N meetings that are given as intervals of the form (start[i], end[i], people[i]) where start[i] is the starting time of the ith meeting, end[i] is the ending time of the ith meeting, people[i] is the number of people who can attend the ith meeting. At any point of time, the room can be occupied by only one me
12 min read
Maximum strength in a Matrix after performing specified operations
Given a matrix of N * M containing {0, 1, #}. The task is to find the maximum value of strength based on following rules: Initial strength is zero.If you encounter a 0, Strength decreases by 2.If you encounter a 1, Strength increases by 5.If you encounter a #, Jumps to the start of a new row without losing any strength. Note: You have to traverse e
7 min read
Maximum people a person can see while standing in a line in both direction
Given an array height[] which represents the height of N people standing in a line. A person i can see a person j if height[j] &lt; height[i] and there is no person k standing in between them such that height[k] ≥ height[i]. Find the maximum number of people a person can see. Note: A person can see any other person irrespective of whether they are
20 min read
Maximize number of days for which P chocolates can be distributed consecutively to N people
Given an integer, P denoting the number of chocolates and an array a[] where ai denotes the type of ith chocolate. There are N people who want to eat chocolate every day. Find the maximum number of consecutive days for which N people can eat chocolates considering the following conditions: Each of the N people must eat exactly one chocolate on a pa
9 min read
Count number of ways in which following people can be arranged
Given integers X and Y representing X girls and Y boys, the task is to count the number of ways arranging X girls and Y boys such that girls always stay together and two boys from Y refuse to stay consecutive. Print the answer modulo 109 + 7. Examples: Input: X = 2, Y = 2Output: 4Explanation: Let's say girls are G1 and G2 and Boys are B1 and B2, co
6 min read
Maximize the Number of People That Can Be Caught in Tag
You are playing a game of tag with your friends. In tag, people are divided into two teams: people who are “it”, and people who are not “it”. Given an array of 0s and 1s, where 0s are people not "it" and 1s are people who are "it". A person who is "it" at index i can catch any one person whose index is in the range [i - dist, i + dist] (inclusive)
7 min read
Program to check Strength of Password
A password is said to be strong if it satisfies the following criteria: It contains at least one lowercase English character.It contains at least one uppercase English character.It contains at least one special character. The special characters are: !@#$%^&amp;*()-+Its length is at least 8.It contains at least one digit. Given a string, find its st
5 min read
Maximizing Strength difference in Two groups
Given an integer N and an array A[] of size 3*N. We need to remove N integers and form 2 groups with the remaining 2*N integers of each size N. 1st group will be of integers having the smallest index and 2nd group will be of the larger index. Let the total sum of the strength of group1 be S1 and the total sum of the strength of group2 be S2. The ta
9 min read
Minimum and Maximum number of pairs in m teams of n people
There are [Tex]n [/Tex]people which are to be grouped into exactly [Tex]m [/Tex]teams such that there is at least one person in each team. All members of a team are friends with each other. Find the minimum and maximum no. of pairs of friends that can be formed by grouping these [Tex]n [/Tex]people into exactly [Tex]m [/Tex]teams.Examples: Input :
6 min read