Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

We define the following: A subarray of an n-element array is an array composed f

ID: 3841508 • Letter: W

Question

We define the following: A subarray of an n-element array is an array composed from a contiguous block of the original array's elements. For example, if array = [1, 2, 3], then the subarrays are [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3]. Something like [1, 3] would not be a subarray as it's not a contiguous subsection of the original array. The sum of an array is the total sum of its elements. An array's sum is negative if the total sum of its elements is negative. An array's sum is positive if the total sum of its elements is positive. Given an array of m integers, find and print its number of negative subarrays on a new line. Input Format The first line contains a single integer, n, denoting the length of array A = [a_0, a_1, ..., a_n - 1]. The second line contains n space-separated integers describing each respective element, a_i in array A. Output Format Print the number of subarrays of A having negative sums. Sample Input 5 1-2 4-5 1 Sample output 9 Explanation There are nine negative subarrays of A = [1, -2, 4, -5, 1]: 1. [1: 1] rightarrow -2 2. [3:3] rightarrow -5 3. [0:1] rightarrow 1 + -2 = -1 4. [2:3] rightarrow 4 + -5 = -1 5. [3:4] rightarrow -5 + 1 = -4 6. [1:3] rightarrow -2 + 4 + -5 = -3 7. [0:3] rightarrow 1 + -2 + 4 + -5 = -2 8. [1:4] rightarrow -2 + 4 + -5 + 1 = -2 9. [0:4] rightarrow 1 + -2 + 4 + -5 + 1 = -1 Thus, we print 9 on a new line.

Explanation / Answer


import java.io.*;
import java.util.*;
import java.util.Scanner;
class negnumber
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println(" Enter Number of Elements:");
int n = scan.nextInt();
System.out.println(" Enter Array of Elements:");
int a[] = new int[n];
int temp = 0;
int i, j;
for(i=0; i<n; i++)
{
a[i] = scan.nextInt();
}
for(i=0; i<n; i++)
{
int tot_num = 0;
for(j=i; j<n; j++)
{
tot_num += a[j];
if(tot_num<0)
{
temp++;
}
}
}
System.out.println(" Result:" +temp);
}
}


OUTPUT


Enter Number of Elements:5
Enter Array of Elements:1 -2 4 -5 1
Result:9

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote