Skip to main content

Featured

say hello world with C++ - Solution in Hacker Rank - hackerranksolutions8

  Objective This is a simple challenge to help you practice printing to  stdout . You may also want to complete  Solve Me First  in C++ before attempting this challenge. We’re starting out by printing the most famous computing phrase of all time! In the editor below, use either  printf  or  cout  to print the string  Hello ,World!  to  stdout . The more popular command form is  cout . It has the following basic form: cout<<value_to_print<<value_to_print; Any number of values can be printed using one command as shown. The  printf  command comes from C language. It accepts an optional format specification and a list of variables. Two examples for printing a string are: printf("%s", string);   printf(string); Note that neither method adds a newline. It only prints what you tell it to. Output Format Print   Hello ,World!   to stdout. Sample Output Hello, World! Solution:- //Say Hello, ...

Hackerrank Java Subarray Solution

 We define the following:

  • 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 n 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= [a0,a1,…..,an-1] .
The second line contains  n space-separated integers describing each respective element,ai , 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]:


Thus, we print 9 on a new line.

Solution:-

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

public class Solution {

    public static void main(String[] args) {
    	Scanner in = new Scanner(System.in);
    	int n = in.nextInt();
    	int count =0;
    	int arr[] = new int[n];
    	for(int i=0; i<n; i++) arr[i] = in.nextInt();
    	for(int i=0; i<n; i++) {
    		int sum = 0;
    		for (int j=i; j<n; j++) {
    			sum = arr[j]+sum;
    			if (sum<0) count++;
    		}
    	}
    	System.out.println(count);
    }
}


Comments