1406B - Maximum Product - CodeForces Solution


brute force dp greedy implementation sortings *1200

Please click on ads to support us..

Python Code:

import sys
from math import *

for _ in range(int(input())):
    n = int(input());
    a = list(map(int,input().split()));
    a.sort();
    ans = -10**18;
    for i in range(n):
        ans = max(ans, a[i%n]*a[(i+1)%n]*a[(i+2)%n]*a[(i+3)%n]*a[(i+4)%n]);
    print(ans);
    
    
    
    
    

C++ Code:

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

int main() {
    int t;
    cin>>t;
    while(t--){
        ll n;
        cin>>n;
        ll ar[n];
        for(ll i=0;i<n;i++){
            cin>>ar[i];
        }
        sort(ar,ar+n);
        ll m1=ar[0]*ar[1]*ar[2]*ar[3]*ar[4];
        ll m2=ar[n-1]*ar[n-2]*ar[n-3]*ar[n-4]*ar[n-5];
        ll ans=max(m1,m2);
        ll m3=ar[0]*ar[1]*ar[2]*ar[3]*ar[n-1];
        ll m4=ar[0]*ar[1]*ar[n-3]*ar[n-1]*ar[n-2];
        ll ans1=max(m3,m4);
        ans=max(ans,ans1);
        cout<<ans<<"\n";
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1487A - Arena
1520D - Same Differences
376A - Lever
1305A - Kuroni and the Gifts
1609A - Divide and Multiply
149B - Martian Clock
205A - Little Elephant and Rozdil
1609B - William the Vigilant
978B - File Name
1426B - Symmetric Matrix
732B - Cormen --- The Best Friend Of a Man
1369A - FashionabLee
1474B - Different Divisors
1632B - Roof Construction
388A - Fox and Box Accumulation
451A - Game With Sticks
768A - Oath of the Night's Watch
156C - Cipher
545D - Queue
459B - Pashmak and Flowers
1538A - Stone Game
1454C - Sequence Transformation
165B - Burning Midnight Oil
17A - Noldbach problem
1350A - Orac and Factors
1373A - Donut Shops
26A - Almost Prime
1656E - Equal Tree Sums
1656B - Subtract Operation
1656A - Good Pairs