09
Jan
2020

Hackerrank Birthday Chocolate (C++)

C++ :

int birthday(vector<int> s, int d, int m) {
    int noOfWays = 0, sum = 0, i = 0;

    do{
        sum = 0;
        for(int j = 0; j < m; j++){
            sum += s[i + j];
        }
        if(sum == d){
            noOfWays++;
        }
        i++;
    }while(i < (s.size() - m + 1));

    return noOfWays;
}

Explanation:

This problem is about summing up a continuous m number of numbers in vector s such that they add up to d. Why a do while loop instead of a for loop? For fun and practice of course :p

Notice the limit for counter i, s.size() – m + 1. This is to prevent running over the boundary of the vector s and getting some funny input. What’s s.size() – m + 1? Eg, s has 5 elements, and m = 2. i starts from 0, and count all the way to 3, and if there is no (+ 1), it will not count the last element, since 3 is not lesser than 3. Another way, of course, is to put i <= instead of just i <

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *