giving TLE in optimal trip(TRIPCOST)

int n,d;

int fun(int c,int cost[],int dist[])
{
int i,d1=0,l1=0;
for(i=0;i<n;i++)
{
if(cost[i]>c)
{
dist[i+1]+=dist[i];
dist[i]=0;
if(dist[i+1]>d)
return (n+1);
}
}

  for(i=0;i<n;i++)
  {
  	if(dist[i]==0)
  	continue;
  	if(d1+dist[i]>=d)
  	{
  		if(d1+dist[i]>d)
  		i--;
  		l1++;
     d1=0;
	  }
	  else
	  d1+=dist[i];
  }
  return (l1+1);

}
int main()
{ int t,i,l1,d1,l,mid,ans,c;
scanf("%d",&t);
while(t–)
{
d1=0;
l=0;

  scanf("%d%d",&n,&d);
int dist[n+1],cost[n+1];
  for(i=0;i<n;i++)
  {
  	scanf("%d%d",&dist[i],&cost[i]);
  }
   
  for(i=0;i<n;i++)
  {
  	if(d1+dist[i]>=d)
  	{   if(d1+dist[i]>d)
  	    i--;
  		l++;
  		d1=0;
	  }
	  else
	  d1+=dist[i];
  }

  l=l+1;
   int high=n,low=0;
  while(high-low>1)
  { 
  	mid=(high-low)/2;
     c=fun(mid,cost,dist);
  	if(c>l)
  	low=mid;
  	else
  	high=mid;
  	
  }
  
  ans=high;
  
  printf("%d %d\n",l,ans);

}
return 0;
}