Sort by

recency

|

670 Discussions

|

  • + 0 comments

    Here are my approaches in c++, you can see the explanation here : https://youtu.be/VFVaLMRzhV4

    Approach 1 O(n)

    int howManyGames(int p, int d, int m, int s) {
        int result = 0;
        while( s >= p){
            s -= p;
            p = max(m, p-d);
            result++;
        }
        return result;
    }
    

    Approach 2 O(n) with recursion

    int howManyGames(int p, int d, int m, int s){
        if( s < p) return 0;
        return howManyGames( max(m, p-d), d, m, s - p) + 1;
    }
    

    Approach 3 O(1), incomplete solution (failure of a test case), feel free to comment to share a way to complete it.

    int howManyGames(int p, int d, int m, int s) {
        int n = 1 + (p - m) / d;
        int total = (p + p - (n - 1) * d) * n / 2;
        if(total <= s) {
            return n + (s - total) / m;
        }
        else 
            return 0;
            // this return need to be computed properly
    }
    
  • + 0 comments
    def howManyGames(p, d, m, s):
        total=0
        count=0
        while True:
            if(total+p>s):
                return count
            else:
                total+=p
                count+=1
            if(p-d<m):
                p=m
            else:
                p-=d
    
  • + 0 comments

    Time Complexity : O(1)

    Visit my code in github : https://github.com/praveen-de-silva/HackerRank_ProblemSolving/blob/main/HaloweenSale.cpp

    int howManyGames(int p, int d, int m, int s) { // invalid condition if (s < p) { return 0; }

    int n1 = 1 + (p - m) / d; // max number of games down to 'm'
    int s1 = n1 * (2*p - (n1 - 1) * d) / 2;      // total cost down to 'm'
    int res;
    
    // case 01 : 's' is in between 'p' and 's1'
    if (s < s1) {
        double det = sqrt((2*p + d) * (2*p + d) - 8*s*d);
        res = (2*p + d - det) / (2 * d);
    } 
    
    // case 02 : 's' is greater than 's1'
    else{
        res = n1 + (s - s1) / m;
    }
    
    return res;
    

    }

  • + 0 comments

    Java solution:

        public static int howManyGames(int p, int d, int m, int s) {
            int cnt = 0;
            
            while (s > 0) {
                s -= p;            
                p -= d;
                
                if (p <= m) p = m;
                
                if (s >= 0) cnt++;
            }
            
            return cnt;
        }
    
  • + 0 comments

    This is my approach

    def howManyGames(p, d, m, s): 
        n_games=0 
    
        while(s>=p):
                s-=p 
                n_games+=1
                p=max(p-d,m)
                
        return n_games 
    

    `