sahil mehta
sahil mehta

Reputation: 17

code giving Exception! can you figure out why? MSS

My code on MSS problem is giving Runtime Error (Non Zero Exit Code) when array size is more than max value of integer though I've solved the problem of array size bu using a 2D array but still getting error. The code is running fine on my system. I can't figure out the problem. Can you?

import java.io.*;
import java.util.*;
import java.lang.*;
 class A{
 public static long max_sum_subarray_neg(long[] A,int n) //when all -ve elements
 {                                                           
     long ans=Long.MIN_VALUE;
     for(int i=0;i<n;i++)
     {
         if(A[i]>ans)
             ans=A[i];
     }
     return(ans);
 }  

public static long max_sum_subarray(long[][] A,int n,int k)  // for atleast one +ve element
{                                                      
    long sum=0,ans=0;
    for(int i=0;i<k;i++)
        for(int j=0;j<n;j++)
        {
        if(sum + A[i][j]>0)
            sum+=A[i][j];
        else sum=0;
        ans= Math.max(ans,sum);
        }
    return ans;
}

public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int t=Integer.parseInt(br.readLine());
    while(t-->0)
    {
        StringTokenizer s=new StringTokenizer(br.readLine());
        int n= Integer.parseInt(s.nextToken());
        int k= Integer.parseInt(s.nextToken());
        s=new StringTokenizer(br.readLine());
        int i,j,neg=0;
        long B[]=new long[n];                 //given array
        long A[][]=new long[k][n];            //array on which MSS has to be done after cpying value from given array k times
        for(i=0;i<n;i++)                    
        {
            B[i]=Long.parseLong(s.nextToken());
            if(B[i]<0)
                neg++;
        }
        long ans;
        if(neg==n)
            ans=max_sum_subarray_neg(B,n);
        else
        {
            for(i=0;i<k;i++)              //copying given array elements k times 
                for(j=0;j<n;j++)     
                    A[i][j]=B[j];    

            ans=max_sum_subarray(A,n,k);
        }
        System.out.println(ans);
    }
}
}

Upvotes: 0

Views: 28

Answers (0)

Related Questions