This tutorial will show you how to solve HackerRank Subarray using Kotlin.

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.

Please go through first how to create Kotlin project in Eclipse

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 integers, find and print it’s number of negative subarrays.

For example,

Input : 1 -2 4 -5 1

Output: 9

In the above example, the input contains n space-separated integers describing each respective element, a[i] , in array A.

class NoOfSubArrays { fun countSubArraysForNegSum(arr: IntArray): Int { var count = 0 val len = arr.size for (i in arr.indices) { var sum = 0 for (j in i..(len - 1)) { sum += arr[j] if (sum < 0) { count++; } } } return count } } fun main(args: Array<String>) { val noOfSubarrays = NoOfSubArrays() val arr: IntArray = intArrayOf(1, -2, 4, -5, 1) println(noOfSubarrays.countSubArraysForNegSum(arr)) }

Running the Kotlin program

Do right click on the above Kotlin class and select `Run As -> Kotlin Application`

Output on Console`9`

Thanks for reading.