Chef and Numbers - WA - Help

Problem:-

Problem Paraphrase:-
Given an array A, select x such that x is having higher frequency when 2 conditions are applied.
1 → No adjacent values should be selected/counted once, like \{3, 3, 3\} here count of 3's is 2.
2- > When there exists 2 equal counts, then select the count formed with smaller number.

Approach:-
While reading values, count frequencies. And while iterating through give array, when a_i = a_{i+1}, then decrease the count in the frequencies table and move to the 2^{nd} element from i, that is.

a_i = a_{i+1} \large\Rightarrow \normalsize freq[a_i]-=1 \large\Rightarrow \normalsize i +=2

Submission:-
Giving me WA for the below code
https://www.codechef.com/viewsolution/32374540

My Code:-

#include <bits/stdc++.h>

using namespace std;

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	unordered_map<int, int> m;
	int t, n, i, ans, freq;
	
	cin >> t;
	
	while( t-- )
	{
		cin >> n;
		
		int a[n+1];
		
		for(i=0; i<n; i++)
		{
			cin >> a[i];
			
			m[a[i]]++;
		}
		
		for(i=a[n]=0; i<n; i++)
		{
			if( a[i] == a[i+1] )
			{
				m[a[i]]--;
				
				i++;
			}
		}
		
		ans = freq = 0;
		
		for(auto x: m)
		{
			if( (x.first < ans and x.second >= freq) or ans == 0 )
			{
				ans = x.first;
				
				freq = x.second;
			}
			
		}
		
		cout << ans ;
		
		if( t )
		{
			cout << '\n' ;
			
			m.clear();
		}
	}

	return 0;
}

Thanks for your time, you helped me grow :slight_smile:.

I think I got it…this condition isnt it

(x.first < ans and x.second >= freq)
1 Like

for example take the test case where given array is {2,2,2,2}–> wrong example
take array {1,2,2,2,1}
then your output ‘2’ but the correct answer is ‘1’.
in your code you should change elements to particular value if A[i]==A[i+1]
then count frequencies.

1 Like

@pkpawan123 ,

It gives 2 tho…

I’m increasing the i, so twice when that a_i == a_{i+1}

1 Like

i did messed up with example
see here example {1,2,2,2,1}
expected output 1 but it gave 2

1 Like

@pkpawan123,

Thanks dude…

I just changed the condition and got AC…

from

(x.first < ans and x.second >= freq)

to

(x.second == freq and ans > x.first) or (x.second > freq)
1 Like

good job

1 Like

Yea, it’s for this…I thought I implemented that condition, but forgot to…my bad, should I delete this post since it’s clarified?..I’m new here.

1 Like

it depends on you. it really doesn’t matter , may be this post can help others so leave it .

1 Like

@pkpawan123
Yea, I’ll leave it…but let’s say I deleted, then would the :hearts:'s I gave you be lost as well?

yep ,they get vanished when post is deleted.

Oh…I see…