0

I had solved this problem using array but not able to do it with vectors.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() 
{
    int age, count = 0, i;
    vector<int>length;
    cin >> age;

    for (i = 0; i <= age; i++)
    {
        length.push_back(i);
    }
    sort(length.begin(), length.end());

    int max = length.back();
    for (i = 0; i <= length.size(); i++)
    {
        if (length[i] == max)
            count++;
    }
    cout << count;
    return 0;
}

I expect the output to be 2 in the first test case but the actual output is 1.

Here's the problem - https://www.hackerrank.com/challenges/birthday-cake-candles/problem

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 4
    Doesn't make sense to sort a vector if you push back 0, 1, 2, ..., age – pptaszni Jul 22 '19 at 08:28
  • 1
    If size is known in advance, get used to `length.reserve(age + 1);` That way, you prevent multiple re-allocations (including copying all the data). – Aconcagua Jul 22 '19 at 08:36
  • Reading the problem: 1. With `i = 0; i <= age` you create one candle too much (try with `age = 2` in your mind: you'll create candles for `i == 0`, `i == 1` and `i == 2`. 2. There's no vector necessary at all: Read first candle as reference, then for all further ones, read them and if size is equal to current, increment a counter, if size is larger, reset this counter to 1... – Aconcagua Jul 22 '19 at 08:39

4 Answers4

2

According to the problem(in the linked website), there you have missed the n which denotes the number of candles on the cake.

enter image description here

You missed that. Also, you are not pushing back the height s into the vector( not age). It should be

int n; 
std::cin>> n;  //>>>> this

for(int i=0; i<n; i++)  // where n is the number of candles on the cake: equalent to the `age` of the girl
{
    int height; std::cin >> height; // height of each candles
    length.push_back(height);
}

The complete code will look like:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    int n;  std::cin >> n;  //>>>> you missed this
    std::vector<int> length;
    length.reserve(n);      // reserve the memory, as you know the size

    for (int i = 0; i < n; i++)  // where n is the number of candles on the cake: equalent to the `age` of the girl
    {
        int height; std::cin >> height;  // height of each candles
        length.push_back(height);
    }
    std::sort(length.begin(), length.end());
    // see the `const` as `max` will not change latter in the program
    const int max = length.back();  

    int count = 0;
    for (const int element : length) // use range based for-loop, if possible
    {
        if (element == max) count++;
    }
    std::cout << count;
    return 0;
}

However, if the max-element in the user input can be found, while inputting, you could avoid calling std::sort. Also, there is a standard algorithm function called std::count which also can be used to find the count of the already found max-element, as follows.

#include <iostream>
#include <algorithm> // std::max, std::count
#include <vector>
#include <numeric>   // std::numeric_limits

int main()
{
    int n;  std::cin >> n; // the number of candles on the cake
    std::vector<int> length;
    length.reserve(n);    // reserve the memory, to avoid un-wanted reallocations
    // set the maximum to INT_MIN
    int max = std::numeric_limits<int>::min();
    while (n--)
    {
        int element;  std::cin >> element;
        length.emplace_back(element);
        // while  inserting to the vector find the maximum element
        max = std::max(element, max);
    }
    // using std::count find the count of `max` element and print!
    std::cout << std::count(length.cbegin(), length.cend(), max);
    return 0;
}

Note: Avoid practising with using namespace std;. More read: Why is "using namespace std;" considered bad practice?

JeJo
  • 30,635
  • 6
  • 49
  • 88
1
int main()
{
    int age, count=0; //, i; // keep variables as local as possible!
    std::vector<int> length;
    std::cin >> age;

    // you don't check for stream state nor validity of `age`:
    if(!std::cin || age < 0) // possibly some upper limit, too??
                             // side note: if you use unsigned int, you only have
                             // to check this upper limit!
    {
        // some appropriate error handling
    }

    // optimisation: we know necessary capacity in advance, so let's prevent
    // otherwise necessary re-allocations:
    length.reserve(age);

    //for(i=0;i<=age;i++)
    for(int i = 0; i < age; i++) // variables as local as possible, remember?
                                 // <= reads one candle too much; consider age == 2:
                                 // you'll get candles for i == 0, i == 1 and i == 2!
    {
        // well no, you don't want to push back the counter itself (0, 1, 2, ...)
        // you need to read in candle hights instead!
        //length.push_back(i);
        int height;
        std::cin >> height;
        // check input as before!
        length.push_back(height);
    }
    std::sort(length.begin(), length.end());

    int max = length.back();

    // for(i=0;i<=length.size(); i++)
    //           ^ again, one element too much!
    // ...

Well, at this point, you can be cleverer; you sorted already, so profit from! Usage of iterators makes it easier, you can directly iterate from back!

for(auto i = length.rbegin(); i != length.rend(); ++i)
{
    if(*i != max)
    {
        count = i - length.rbegin();
        break;
    }
}
// special case: all candles have same height, then you would't have met the inner if:
if(count == 0)
{
    count = length.size();
}

Actually, you can do without sorting first in just one single go:

int max = 0; // now let's assume we checked for negative values right from the start
             // otherwise we'd need to use std::numeric_limits<int>::min() instead
             // again I'd prefer the unsigned type...
for(auto height : length)
{
    if(height == max)
        ++count;
    else if(height > max)
        count = 1;
    // else: can ignore...
}

Hm... did you notice? We just processed in the same order than we read in the values. So we could do all in one single go:

for(int i = 0; i < age; ++i)
{
    unsigned int height;
    std::cin >> height;
    // check validities!

    // instead of pushing back, directly calculate what we are interested in:
    if(height == max)
        ++count;
    else if(height > max)
        count = 1;
}
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

You are stepping beyond the end of the vector. Use <, and not <=.

for(i=0; i    <    length.size(); i++)
robthebloke
  • 9,331
  • 9
  • 12
0
#include<iostream>
#include<algorithm>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define max 100000
int main()
{
    int a[max],i,n,count=0,key;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    
        sort(a, a+n);
    for(i=0;i<n;i++)
    {
        key=a[n-1];
        if(key==a[i])
        {
            count=count+1;
        }
    }
    cout<<count;
David Buck
  • 3,752
  • 35
  • 31
  • 35
  • Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to other users with similar issues. – FluffyKitten Sep 08 '20 at 04:57