Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange
1 of 2

Gives correct output but slow

I'm new to this competitive programming world. This morning I came across this question, which required the time to be less than 1 sec. But my code runs for 1.000069 sec, thereby rejecting my solution.

Question:

There are N chocolate boxes, and you will be given with a chocolate index for which we have to guess the correct box number. For example, The first box contain chocolates from 1 to N1 and the next box contain N1+1 through N2 and so on.

My Solution:

#include<iostream>
using namespace std;

//returns the sum of chocolates from 0 to i 

int getSum(int i,int *array){
    int sum = 0;
    for(int j=0; j< i; j++){
        sum += array[j];
    }
    return sum;
}
int main(){
    int n,q;
    //Get the number of chocolate boxes.
    cin >> n;  
    int chocolatesInEachBox[n];     
    //Get the number of chocolates in each box.
    for(int i =0; i < n; i++){
        cin >> chocolatesInEachBox[i];
    }   
    //Get the number of queries.
    cin>>q;
    int chocolateIndexes[q];
    //Get each query.
    for(int i =0; i < q; i++){
        cin >> chocolateIndexes[i];
    }
    int j=0,i=0;

    while(j < q && i<n){

        if((chocolateIndexes[j]-getSum(i+1,chocolatesInEachBox))>0)
        i++;

        else{
            cout<<i+1<<endl;
            j++;
            i=0;
        }        
    }
}