Jacob_Thomas

Shobhit's code for 'Best Index'

Jun 10th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.io.IOException;
  4. public class Best_Index{
  5.     public static void main(String args[])throws IOException{
  6.         InputStreamReader isr=new InputStreamReader(System.in);
  7.         BufferedReader br=new BufferedReader(isr);
  8.         int size=Integer.parseInt(br.readLine());
  9.         String x[]=(br.readLine()).split(" ");
  10.         long arr[]=new long[size];
  11.         for(int i=0;i<size;i++){
  12.             try{
  13.             arr[i]=Integer.parseInt(x[i]);}
  14.             catch(Exception e){
  15.                 continue;
  16.             }
  17.         }
  18.         long final_max=-999999999;
  19.         for(int start=0;start<size;){
  20.             int left_number=size-start;
  21.             int max_to_which_it_can_go=(-1+(int)Math.sqrt(1+8*(left_number)))/2;
  22.             int numbers=((max_to_which_it_can_go)*(max_to_which_it_can_go+1))/2;
  23.             long temp_sum=0;
  24.             for(int i=start;i<numbers+start;i++){
  25.                 temp_sum+=arr[i];
  26.         }
  27.         boolean is_logic=false;
  28.         long partial_sum=temp_sum;
  29.         while(size-numbers-start>0){
  30.             is_logic=true;
  31.             int temp_start=start;
  32.             int temp_end=numbers+start-1;
  33.             partial_sum-=arr[temp_start];
  34.             partial_sum+=arr[temp_end+1];
  35.             if(partial_sum>temp_sum){
  36.                 temp_sum=partial_sum;
  37.             }
  38.             start++;
  39.         }
  40.         if(temp_sum>final_max){
  41.             final_max=temp_sum;
  42.     }
  43.     if(is_logic!=true){
  44.         start++;
  45.     }
  46.         }
  47.         System.out.println(final_max);
  48.     }
  49. }
Add Comment
Please, Sign In to add comment