231C. To Add or Not to Add - Codeforces Solution C++

  Problem Link : 231C. To Add or Not to Add 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

#define ll long long int

ll ans;

bool func(ll m, ll arr[],ll k,ll n)
{
	if(m>n)
		return 0;
	ll cnt=0;
	for(ll i=0;i<m;i++)
		cnt+=arr[m-1]-arr[i];

	if(cnt <= k)
	{
		ans = arr[m-1];
		return 1;
	}

	for(ll i=m;i<n;i++)
	{
		cnt+=(m-1)*(arr[i]-arr[i-1])-(arr[i-1]-arr[i-m]);
		if(cnt<=k)
		{
			ans=arr[i];
			return 1;
		}
	}

	return 0;
}

int main()
{
	ll n,k;
	cin>>n>>k;
	ll arr[n];
	for(int i=0;i<n;i++)
		cin>>arr[i];

	sort(arr,arr+n);

	ll low=0,high= n+1,mid;
	ans=-1;
	while(low<high)
	{
		mid=low+(high-low+1)/2;

		if(func(mid,arr,k,n))
			low=mid;
		else
			high=mid-1;

	}

	cout<<high<<" "<<ans;

}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!