Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Maximum Subarray Sum

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

O(N^3) Solution

O(N^2) Solution

O(N) time constant space(DP)/Kadane’s algorithm

Code

// codestudio
#include <bits/stdc++.h>
long long maxSubarraySum(int arr[], int n)
{
    long long maxSum = 0;
    long long currSum = 0;
    for (int i = 0; i < n; i++) {
        currSum += arr[i];
        maxSum = max(maxSum, currSum); // end = i
        currSum = max(0ll, currSum); // start = i+1
    }
    return maxSum;
}

To get subarray