ZCO14003 - Editorial

PROBLEM SETTER -
ZCO 2014

DIFFICULTY -
Easy

PREREQUISITES -
Sorting

KEY OBSERVATIONS -

  1. Sorting the array will not affect the answer as the answer doesn’t depend on the index of an element.
  2. The answer would always be some element of the array, which is trivial to prove.
  3. The revenue earned if we fix the price to be a[i], (for some 1 <= i <= N) will be a[i] * (N-i+1). Remember, the array is sorted in ascending order, and thus, there are(N-i-1) customers which have budget greater than a[i].

FIRST SUBTASK SOLUTION -
Simply try all combinations by putting price equal to every element one by one and check the number of integers/elements bigger than this price. multiplying price and the bigger numbers will give the revenue for that price. Take the maximum of all such revenues and output it. Since we are trying every element and checking the bigger numbers in whole array takes O(N), time complexity comes out to be O(N^2).

int ans=0;
for(int i = 1;i < n+1;i++)
{
	int cnt=0;
	for(int j = 1;j < n+1;j++)
		if(a[j] <= a[i])
			cnt++;
	ans = max(ans,cnt*a[i]);
}
cout << ans;

SECOND SUBTASK SOLUTION -
Solution is to iterate on sorted array and take maximum of the term [ a[i] * (N-i+1) ] for all i between 1 and N.

    sort(a+1,a+n+1);
	ll ans=0,cnt=0;
	for(ll i = 1;i < n+1;i++)
	{
		cnt = a[i]*(n-i+1);
		ans = max(ans,cnt);
	}
	cout << ans;

This works because, after sorting, the checking process that was initially happening in O(N) for each index will now happen in O(1) time as the number of elements bigger than the i^{th} element is already known to be (N-i+1).

Don’t forget to store answer in long long format.

TIME COMPLEXITY -
O(N * Log(N))

2 Likes

This code does literally the same thing, still getting WA on most TCs. Please help.
https://www.codechef.com/viewsolution/21759944

3 Likes

Please help @vivek1_007

yeah, the code doesnt work

Shouldnt it be (n-i-1) ???
Take for example i=0… then (n-i+1) becomes n+1 which can never happen since there are only n elements!!!

Use “(N-i)” instead of (N-i-1) or (N-i+1) because any person with budget greater than or equal to the current price in the sorted array can buy the app. For example, if price is set = a[0] then all N people can buy the app, revenue being = a[0](N); for price = a[1], only N-1 people can buy the app with revenue being = a[1](N-1). Hence the formula a[i]*(N-i).

2 Likes

Even after writing correct code if you are still getting error, this might be because you are using int data type. Use long and everything will work fine.