File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 3442. Maximum Difference Between Even and Odd Frequency I
2
+ // You are given a string s consisting of lowercase English letters.
3
+ // Your task is to find the maximum difference diff = freq(a1) - freq(a2) between the frequency of characters a1 and a2 in the string such that:
4
+ // a1 has an odd frequency in the string.
5
+ // a2 has an even frequency in the string.
6
+ // Return this maximum difference.
7
+
8
+
9
+ // Solution: Counting
10
+
11
+ // Count the occurances of each character.
12
+ // Find the maximum odd frequency and minimum even frequency.
13
+
14
+ // Time Complexity: O(n) 1ms
15
+ // Space Complexity: O(1) 55MB
16
+ function maxDifference ( s ) {
17
+ const count = Array ( 26 ) . fill ( 0 ) ;
18
+ for ( let i = 0 ; i < s . length ; i ++ ) {
19
+ count [ s . charCodeAt ( i ) - 97 ] ++ ;
20
+ }
21
+ let maxOdd = - Infinity , minEven = Infinity ;
22
+ for ( let i = 0 ; i < 26 ; i ++ ) {
23
+ if ( count [ i ] === 0 ) continue ;
24
+ if ( count [ i ] % 2 === 1 ) {
25
+ maxOdd = Math . max ( maxOdd , count [ i ] ) ;
26
+ } else {
27
+ minEven = Math . min ( minEven , count [ i ] ) ;
28
+ }
29
+ }
30
+ return maxOdd - minEven ;
31
+ } ;
32
+
33
+ // Two test cases
34
+ console . log ( maxDifference ( "aaaaabbc" ) ) // 3
35
+ console . log ( maxDifference ( "abcabcab" ) ) // 1
You can’t perform that action at this time.
0 commit comments