0

for input 2:100000,90000 getting wrong answer even i used long

import java.util.*;
import java.io.*;
class Main
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);

        int a = s.nextInt();

        int arr[] = new int[a];

        for(int i=0;i<a;i++)
            arr[i] = s.nextInt();

        Arrays.sort(arr);

        long sum=0;

        sum=(arr[a-1])*(arr[a-2]); 

        System.out.println(sum);

    }
}

how to overcome problem in integer overflow even using long also wrong answers ?

markspace
  • 10,621
  • 3
  • 25
  • 39

1 Answers1

2
sum=(arr[a-1])*(arr[a-2]); 

This multiples an int by an int and then assigns the int result (which may have overflowed) to a long variable.

To use long arithmetic, write

sum = (long) arr[a-1] * (long) arr[a-2]; 

You don't need both casts, but is seems a lttle clearer with them.

user13784117
  • 1,124
  • 4
  • 4