14
Jan
2020

Hackerrank Picking Numbers (C++)

C++ :

int pickingNumbers(vector<int> a) {
    int maxLength = 0, startingNo;
    bool searchSmaller = false, searchBigger = false;
    vector<int> numberList;

    for(int i = 0; i < a.size(); i++){
        startingNo = a[i];
        searchSmaller = false;
        searchBigger = false;
        //decide to search for startingNo -1 or startingNo +1
        for(int k = 0; k < a.size(); k++){
            if(a[k] == startingNo - 1){
                searchSmaller = true;
                searchBigger = false;
                break;
            }else{
                searchBigger = true;
            }
        }

        if(searchSmaller){
            for(int j = 0; j < a.size(); j++){
                if(startingNo - a[j] == 1 || startingNo - a[j] == 0){
                    numberList.push_back(a[j]);
                }
            }
        }

        if(searchBigger){
            for(int j = 0; j < a.size(); j++){
                if(a[j] - startingNo == 1 || a[j] - startingNo == 0){
                    numberList.push_back(a[j]);
                }
            }
        }

        if(maxLength <= numberList.size()){
            maxLength = numberList.size();
        }
        numberList.clear();
    }
    
    return maxLength;
}

Explanation:

For the outer for loop (iterating with i), each ith element is assigned to startingNo. We then decide to look for the number smaller or larger than startingNo, depending on what is available in the vector.

The first nested for loop (iterating with k) search through the vector if the array has the number smaller than startingNo. searchSmaller is set to true if the number is found, otherwise, searchBigger is set to true.

Once determined to search for the number smaller or bigger than startingNo, we then run through the second nested for loop (iterating with j).. Add the number to the vector numberList for each suitable number, then find out the size of the vector at the end of the j for loop. If numberList’s size is greater than maxLength, assign it to maxLength. Clear the numberList vector afterwards.

You may also like...

Leave a Reply

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