1740C - Bricks and Bags - CodeForces Solution


constructive algorithms games greedy sortings *1400

Please click on ads to support us..

Python Code:

from sys import stdin

T = int(input())
for t in range(T):
    n = int(stdin.readline().strip())
    a = list(map(int, stdin.readline().strip().split()))
    a.sort()
    sofar = 0
    for i in range(n):
        l_next, r_next = 0, 0
        if i > 0:
            l_next = a[i] - a[i-1]
        if i < n-1:
            r_next = a[i+1] - a[i]

        left = a[i] - a[0]
        right = a[n-1] - a[i]
        sofar = max(sofar, max(l_next, r_next) + max (left, right))
    print(sofar)

C++ Code:

#include<bits/stdc++.h>
using namespace std;
void solve()
{
	int n;
	cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; i++)
		cin >> a[i];
	sort(a.begin(), a.end());
	int ans = 0;
	for (int i = 0; i < n-2; i++)
		ans = max(ans, a[n - 1] - a[i] + a[i+1] - a[i]);
	for (int i = n - 1; i > 0; i--)
		ans = max(ans, a[i] - a[i - 1] + a[i] - a[0]);
	//
	cout << ans << endl;
}

int main()
{
	int t;
	cin >> t;
	while (t--)
		solve();
	return 0;
}


Comments

Submit
0 Comments
More Questions

1700B - Palindromic Numbers
702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array
1613B - Absent Remainder
1536B - Prinzessin der Verurteilung
1699B - Almost Ternary Matrix
1545A - AquaMoon and Strange Sort
538B - Quasi Binary
424A - Squats
1703A - YES or YES
494A - Treasure
48B - Land Lot
835A - Key races
1622C - Set or Decrease
1682A - Palindromic Indices
903C - Boxes Packing
887A - Div 64
755B - PolandBall and Game
808B - Average Sleep Time
1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS