I am doing a problem of spoj i tried to do it but I am always getting TLE(time limit expired )
the question is Hotels . this is my code , please can you tell me the way to optimize it.
#include<stdio.h>
int main()
{
unsigned long long int a,b,i;
scanf("%llu %llu",&a,&b);
unsigned long long int arr[a];
for(i=0;i<a;i++)
{
scanf("%llu",&arr[i]);
}
unsigned long long int d;
unsigned long long int k,z=0;
for(i=0;i<a;i++)
{
d = arr[i];
for(k=i+1;k<a+1;k++)
{
if (d<b)
{
if(z<d)
z = d;
}
else
if(d==b)
{
z = d;
break;
}
else
break;
d = d + arr[k];
}
if(d==b)
break;
}
printf("%llu",z);
return 0;
}
in this like if input 5 12 , these five are 2 1 3 4 5 to make 12 then i do like this :
first i compare 12 with 2 , then 2+1 , then 2+1+3 and so on after it goes to 5 it compares 12 to 1 , 1+3 , 1+3+4 .. and in this way i am taking only consecutive and break when i find equal to 12 otherwise it goes on till last.
Hitesh
There is no need to restart again as you said in the explanation
after it goes to 5 it compares 12 to 1 , 1+3 , 1+3+4 .. and in this way. Look at your approach carefully, you are recalculating the sums of a subarray again and again. For e.g – You have already calculated sum of subarray1+3+4when you were doing2+1+3+4. Hence there is still some scope of optimization.Before telling the exact solution, I want you to try it out first. Also as one more hint refer to the following problem Find subarray with given sum.
EDIT: Sharing complete solution for future purpose.
// Driver program to test above function