Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

53. Maximum Subarray 🌟

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

class Solution{
public:
    int maxSubArray(vector<int> &nums) // Kadane's algorithm
    {
        int n = nums.size();
        int mx = nums[0];
        int sm = 0;
        for (int i = 0; i < n; i++)
        {
            sm += nums[i];
            mx = max(sm, mx);
            if (sm < 0)
                sm = 0;
        }
        return mx;
    }
};