1029C - Maximal Intersection - CodeForces Solution


greedy math sortings *1600

Please click on ads to support us..

Python Code:


n=int(input())
l=[]
for i in range(n):
    l.append(list(map(int, input().split())))

ll=[[0,0] for _ in range(n)]
rr=[[0,0] for _ in range(n)]
ll[0]=l[0]
for i in range(1,n):
    ll[i][0]=max(ll[i-1][0],l[i][0])
    ll[i][1]=min(ll[i-1][1],l[i][1])
    
rr[-1]=l[-1]
for i in range(n-2,-1,-1):
    rr[i][0]=max(rr[i+1][0],l[i][0])
    rr[i][1]=min(rr[i+1][1],l[i][1])

ans=0
if n>1:
    ans=max(ans,rr[1][1]-rr[1][0])
    ans=max(ans,ll[n-2][1]-ll[n-2][0])
for i in range(1,n-1):
            ans=max(ans, min(ll[i-1][1],rr[i+1][1])-max(ll[i-1][0], rr[i+1][0]))
print(ans)

    

C++ Code:

// بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ
// Written by Ilia Rahbar

// #pragma GCC optimize ("O3,no-stack-protector,unroll-loops,fast-math")
// #pragma GCC target ("abm,bmi,bmi2,tbm,avx2")

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

#define int int64_t
#define sz(x) int(x.size())
#define ai(x) array <int, x>
#define be(x) x.begin(), x.end()
#define pb push_back
#define el '\n'
#define sp ' '
#define fi first 
#define se second

const int M = 1e9 + 7, N = 1e6 + 100;

int n, ans = 0, x, y;

ai(2) a[N], l[N], r[N];

int32_t main()
{
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    
    cin >> n;

    for (int i = 0; i < n; i++)
        cin >> a[i][0] >> a[i][1];

    l[0] = a[0];

    for (int i = 1; i < n; i++)
        l[i][0] = max(l[i-1][0], a[i][0]), l[i][1] = min(l[i-1][1], a[i][1]);

    r[n-1] = a[n-1];

    for (int i = n-2; i >= 0; i--)
        r[i][0] = max(r[i+1][0], a[i][0]), r[i][1] = min(r[i+1][1], a[i][1]);

    for (int i = 1; i < n-1; i++)
    {
        x = max(r[i+1][0], l[i-1][0]);
        y = min(r[i+1][1], l[i-1][1]);

        ans = max(ans, y - x);
    }

    cout << max(ans, max(r[1][1] - r[1][0], l[n-2][1] - l[n-2][0]));
}


Comments

Submit
0 Comments
More Questions

1440A - Buy the String
1658F - Juju and Binary String
478A - Initial Bet
981A - Antipalindrome
365A - Good Number
1204B - Mislove Has Lost an Array
1409D - Decrease the Sum of Digits
1476E - Pattern Matching
1107A - Digits Sequence Dividing
1348A - Phoenix and Balance
1343B - Balanced Array
1186A - Vus the Cossack and a Contest
1494A - ABC String
1606A - AB Balance
1658C - Shinju and the Lost Permutation
1547C - Pair Programming
550A - Two Substrings
797B - Odd sum
1093A - Dice Rolling
1360B - Honest Coach
1399C - Boats Competition
1609C - Complex Market Analysis
1657E - Star MST
1143B - Nirvana
1285A - Mezo Playing Zoma
919B - Perfect Number
894A - QAQ
1551A - Polycarp and Coins
313A - Ilya and Bank Account
1469A - Regular Bracket Sequence