The problem context involves working with arrays in Java. The task is to count the number of subarrays in a given array that sum up to a negative number. A subarray is a contiguous part of an array. The size of the array and its elements are provided by the user.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach involves using two nested loops to generate all possible subarrays of the given array. For each subarray, it calculates the sum of its elements. If the sum is negative, it increments a counter. The counter, which starts at zero, is then printed out, representing the total number of negative subarrays.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.datastructures;
import java.util.Scanner;
/**
*
*/
public class JavaSubarray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int count = 0;
for (int i = 0; i < n; i++) {
int sum = a[i];
if (sum < 0)
count++;
for (int j = i + 1; j < n && i + 1 < n; j++) {
sum += a[j];
if (sum < 0) {
count++;
}
}
}
System.out.println(count);
sc.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.