Hackerrank – The Maximum Subarray

Hackerrank – Problem Statement

A description of the problem can be found on Hackerrank.

Solution

  • Contiguous sum – using Kadane’s algorithm
  • Non-contiguous sum – filter all positive elements from given array and sum them. If this array is empty. Take the greatest element.

I created solution in:

All solutions are also available on my GitHub.

Java

JavaScript

Scala

Ruby

2 thoughts on “Hackerrank – The Maximum Subarray

    1. Hi.
      If you look at the wikipedia page there are two Kadane algorithms. I chose the second, which sets maxSoFar and maxEnding to first element of the array. There is a test case in Hackerrank that all elements are negative and if you set maxSoFar and maxEnding to 0 you will get wrong result.

Leave a Reply

Your email address will not be published. Required fields are marked *