The Maximum Subarray HackerRank Solution

The Maximum Subarray HackerRank Solution

In this The Maximum Subarray HackerRank solution, We define subsequence as any subset of an array. We define a subarray as a contiguous subsequence in an array.

Given an array, find the maximum possible sum among:

  1. all nonempty subarrays.
  2. all nonempty subsequences.

We need to Print the two values as space-separated integers on one line.

The Maximum Subarray HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in Python

def maxSubarray(arr):
    sumSubArr = 0
    maxSumSubArr = 0
    subsequence = 0
    for a in arr:
        if a > 0:
            subsequence+=a
        if sumSubArr + a > 0:
            sumSubArr += a
            if sumSubArr > maxSumSubArr:
                maxSumSubArr = sumSubArr
        else:
            sumSubArr = 0
    if subsequence == 0:
        subsequence = maxSumSubArr = max(arr)
    return [maxSumSubArr, subsequence]

Problem Solution in Java

public static List<Integer> maxSubarray(List<Integer> arr) {
    int answer = Integer.MIN_VALUE;
    int sum = 0;
    int current = 0;
    for (int i : arr) {
        sum += Math.max(0, i);
        current = Math.max(i, current + i);
        answer = Math.max(answer, current);
    }
    return Arrays.asList(answer, answer < 0 ? answer : sum);
}

Problem Solution in JavaScript

function maxSubarray(arr) {
    if (arr.every(el => el < 0)) {
        let sorted = arr.sort((a, b) => b - a);
        return [sorted[0], sorted[0]]


    }
    if (arr.every(el => el > 0)) {
        let reduced = arr.reduce((acc, value) => acc + value);
        return [reduced, reduced]


    }
    let best = 0;
    let current = 0;
    let max = 0;


    arr.forEach(el => {
        current = Math.max(0, current + el);
        best = Math.max(best, current);


        max = Math.max(max, max + el)


    })


    return [best, max];
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems