Skip to content

Commit 573ab9a

Browse files
committed
Binary Search
1 parent 8593067 commit 573ab9a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include<bits/stdc++.h>
2+
#define ll long long int
3+
using namespace std;
4+
5+
int main()
6+
{
7+
ll n,x;
8+
cin>>n>>x;
9+
vector<ll>arr(n);
10+
ll sum=0;
11+
vector<ll>add(n+1); // this is needed for getting the prefix sum
12+
for(ll i=0;i<n;i++)
13+
{
14+
cin>>arr[i];
15+
sum+=arr[i];
16+
add[i+1]=sum;
17+
}
18+
ll low=0,high=n+1,ans=-1;
19+
while(low<high){
20+
ll mid=(low+high)/2;
21+
ll max=0;
22+
for(ll j=0;j+mid<=n;j++){
23+
ll presum=add[j+mid]-add[j];
24+
if(max<presum)
25+
max=presum;
26+
}
27+
if(max<=x)
28+
low=mid+1;
29+
else
30+
high=mid;
31+
}
32+
cout<<low-1<<endl; //as 1 extra is addded at the begiinig of add array..this nullifies it
33+
return 0;
34+
}

0 commit comments

Comments
 (0)