Maximise Function CodeChef Solution | AskTheCode

CodeChef Feb Long Challenge Solution | Maximise Function Solution in Java | Ask The Code


You are given a sequence A1,A2,…,AN. Find the maximum value of the expression |AxAy|+|AyAz|+|AzAx| over all triples of pairwise distinct valid indices (x,y,z).


  • The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.

  • The first line of each test case contains a single integer N.

  • The second line contains N space-separated integers A1,A2,…,AN.


For each test case, print a single line containing one integer ― the maximum value of |AxAy|+|AyAz|+|AzAx|.


  • 1≤T≤5

  • 3≤N≤10^5

  • |Ai|≤10^9 for each valid i


Subtask #1 (30 points):N≤500

Subtask #2 (70 points): original constraints

Example Input:

3 3 2 7 5 3 3 3 3 5 2 2 2 2 5

Example Output:

10 0 6


Example case 1: The value of the expression is always 10. For example, let x=1, y=2 and z=3, then it is |2−7|+|7−5|+|5−2|=5+2+3=10.

Example case 2: Since all values in the sequence are the same, the value of the expression is always 0.

Example case 3: One optimal solution is x=1, y=2 and z=5, which gives |2−2|+|2−5|+|5−2|=0+3+3=6.


/* package codechef; // don't place package name! */

import java.util.*;

import java.lang.*;


/* Name of the class has to be "Main" only if the class is public. */

class Codechef{

public static void main (String[] args) throws java.lang.Exception{

try {

Scanner sc = new Scanner(;

int t = sc.nextInt();


int n = sc.nextInt();

long a[]=new long[n];

for(int i=0;i<n;i++) {




long ans=Math.abs(a[0]-a[n-1])+Math.abs(a[n-1]-a[1])+Math.abs(a[0]-a[1]);



}catch (Exception e) {




18 views0 comments

Recent Posts

See All

Calculate BMI in Java | AskTheCode

Write a Java program that reads values for weight in kilograms and height in centimeters and prints out the BMI... interpretation of it...

"Believe you can and you're halfway there"