https://www.codechef.com/LTIME70B/problems/POGOSTCK

https://www.codechef.com/LTIME70B/problems/POGOSTCK

why this program gives me SIGSEGV error ?

#include
#include
using namespace std;

int main()
{
int t,n,k,max,tempNum,tempIndex;
cin>>t;
while(t–)
{
cin>>n>>k;
int num[k];

	for(int i=0;i<k;i++)
		cin>>num[i];
	for(int i=k;i<n;i++)
	{
		cin>>tempNum;
		tempIndex=i%k;
		if(num[tempIndex]<0)
			num[tempIndex]=0;
		num[tempIndex]+=tempNum;
	}
	max=*(max_element(num,num+k));			
	cout<<max<<endl; 
}

}

thats a segmentation fault bro . you need to assign certain data types ( in this problem you need to change int to unsigned int to not cross the limit of int range ) according to given Constraints . Learn about the data type ranges https://www.geeksforgeeks.org/c-data-types/

2 Likes

When i first watched your code, It seems compeletely true and was also working for all cases , I was going to reply that i am unable to find any bug but suddenly i found a case for which your code was unable to work and that case is
1
3 5
1 2 4
the answer must be 4 but your code is not giving any output due to Segmenatation fault and the fault is at the last line where you are trying to find the maximum element with the help of std::algorith::max_element. You are passing num and num+k as its arguments while num+k is not available so you are getting that segmentation fault.
Remember watching the constraints carefully its nowhere mentioned that k will be less than n.
Do upvote , It is my first answer on codechef discuss.

1 Like

there’s no upvoting in discuss only liking.