1831B - Array merging - CodeForces Solution


constructive algorithms greedy

Please click on ads to support us..

Python Code:

import sys,math,cmath,time
from bisect import bisect_left
start_time = time.time()


def solve():
    n=inp()
    a=[int(k) for k in inps()]
    b=[int(k) for k in inps()]
    a.append(-1)
    b.append(-1)
        
    d1={}
    d2={}
    c=1
    c1=1
    for i in range(n):
        d1[a[i]]=d1.get(a[i],0)
        d2[b[i]]=d2.get(b[i],0)
    for i in range(n):
        if(a[i]==a[i+1]):
            c+=1
        else:
            d1[a[i]]=max(d1[a[i]],c)
            c=1
        if(b[i]==b[i+1]):
            c1+=1
        else:
            d2[b[i]]=max(d2[b[i]],c1)
            c1=1
    ans=0
    for i in d1:
        ans=max(ans,d1[i]+d2.get(i,0))
    for i in d2:
        ans=max(ans,d2[i]+d1.get(i,0))
    print(ans)









def main():

    testcases = 1
    testcases = inp()
    for each_testcase in range(testcases):
        solve()
            
def inp():
    return(int(input()))
def inps():
    return(input().split())

ONLINE_JUDGE = __debug__ if ONLINE_JUDGE:
    input = sys.stdin.readline

main()

C++ Code:

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


int main()
{
    cin.tie(0);cout.tie(0);ios::sync_with_stdio(0);
    int t;
    cin >> t;
    while (t--){
        int n;
        cin >> n;
        int a[n], b[n];
        for(int i = 0; i < n; i++) cin >> a[i];
        for(int i = 0; i < n; i++) cin >> b[i];
        int c[2 * n + 10] = {0};
        int cur = 0;
        int k = -1;
        int ans = 0;
        for(int i = 0; i < n; i++){
            if(a[i] != k){
                k = a[i];
                cur = 0;
            }
            cur++;
            c[k] = max(cur, c[k]);
            ans = max(ans, c[k]);
        }   
        cur = 0, k = -1;     
        for(int i = 0; i < n; i++){
            if(b[i] != k){
                k = b[i];
                cur = 0;
            }
            cur++;
            ans = max(ans, cur + c[k]);
        }
        cout << ans << '\n';
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie
1605B - Reverse Sort
1607C - Minimum Extraction
1604B - XOR Specia-LIS-t
1606B - Update Files
1598B - Groups
1602B - Divine Array
1594B - Special Numbers
1614A - Divan and a Store
2085. Count Common Words With One Occurrence
2089. Find Target Indices After Sorting Array
2090. K Radius Subarray Averages
2091. Removing Minimum and Maximum From Array
6. Zigzag Conversion
1612B - Special Permutation
1481. Least Number of Unique Integers after K Removals
1035. Uncrossed Lines