HackerRank Java - Java Subarray Solution Explained

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

Nice. I figured it was 3 loops too. Was making my head hurt thinking about getting the loop steps or start/ends sorted. So thought... if you think in of the permutations in n... as binary... then use 0s and 1s... Then check there are no zeros between ones with a regex. But alas that timed out when it did final submission. So if you have 3 array items - 000 and 101 would be only entries you don't add. If you had 4, things like 0000, 0101, 1001, 1010, 1011, 1 1101 would get filtered out. You would obviously always start loops with 1 to avoid the all zeros. SInce posting - just came across the BitSet class. May be worth a revisit at some point to see if that speeds things up.

jeremyflowers
Автор

This works as well,
int count = 0;
for (int i = 0; i < n; i++) {
int sum=0;
for (int j = i; j < n; j++) {
sum+=a[j];
if (sum<0) count++;
}
}

System.out.println(count);

jayapals
Автор

oh moment I realized the loops that was fantastic. thank you.

bharathveerabomma
Автор

You are doing great work...it helps me a lot...thanku ..god bless

shaikhnabeel
Автор

I have used 2 for loop which is more optimize
Try this code:

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int [n];
for(int i = 0; i < n; i++){
arr[i] = scanner.nextInt();
}
scanner.close();
int count = 0;
int sum = 0;
for(int j = 0; j < n; j++){
for(int k = j; k < n; k++){
sum += arr[k];
if(sum < 0){
count++;
}
}
sum = 0;
}
System.out.println(count);

}
}

mihirpaghdal
Автор

It runs in O(n^2). If anyone knows O(n) solution please comment.
for(int j=0;j<a.size();j++){
max = 0;
for(int i=j;i<a.size();i++){
max = max + a.get(i);
b.add(max);
}
}

bujagawnisaitejagoud
join shbcf.ru