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.
publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in);intn=sc.nextInt();int[]array=newint[n];for(inti=0;i<n;i++){array[i]=sc.nextInt();}System.out.println(countSubarraysWithNegativeSums(array));sc.close();}privatestaticintcountSubarraysWithNegativeSums(int[]array){intcount=0;intcurrentSum;// Look all the possible subArrays and check it sumsfor(inti=1;i<=array.length;i++){for(intj=0;j<=array.length-i;j++){currentSum=0;for(intz=0;z<i;z++){currentSum+=array[j+z];}if(currentSum<0)count++;}}returncount;}//Second Approach: Time Complexity O(n^2)privatestaticintcountSubarraysWithNegativeSums(int[]array){intcount=0;intcurrentSum;intn=array.length;// Look all the possible subArrays and check for(intstart=0;start<n;start++){currentSum=0;for(intend=start;end<n;end++){currentSum+=array[end];if(currentSum<0)count++;}}returncount;}
Java Subarray
You are viewing a single comment's thread. Return to all comments →
First approach: Time Complexity: O(n^3)