We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
javapublicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannersc=newScanner(System.in);intN=sc.nextInt();int[]arr=newint[N];for(inti=0;i<N;i++){arr[i]=sc.nextInt();}intcountOfNegativeSubArrays=0;intptr1=0;intptr2=0;intsw=Arrays.copyOfRange(arr,ptr1,ptr2+1).length;// default sliding-w width of 1while(sw<=arr.length){for(inti=0;i<arr.length&&ptr2+i+1<=arr.length;i++){// sliding through the array.int[]subArr=Arrays.copyOfRange(arr,ptr1+i,ptr2+i+1);/** debugging: System.out.printf("from %d to %d\n", ptr1+i, ptr2+i); System.out.println(Arrays.toString(subArr)); System.out.println("--------------"); */intsum=Arrays.stream(subArr).sum();if(sum<0){countOfNegativeSubArrays++;}// 0 : 0// 1 : 1// 2 : 2// 0 : 1// 1 : 2}// Update the sliding-window widthsw=Arrays.copyOfRange(arr,ptr1,++ptr2).length+1;}System.out.println(countOfNegativeSubArrays);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Subarray
You are viewing a single comment's thread. Return to all comments →