DEV Community

Thivyaa Mohan
Thivyaa Mohan

Posted on

3 3

Maximum Subarray - Leetcode Solution

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.

We need to use Kadane's Algorithm here

//Kadane's Algorithm

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int ans =INT_MIN,sum =0;
        int n=nums.size();
        for(int i=0;i<n;++i){
           sum+=nums[i];
           ans = max(ans,sum);
        if(sum<0)
            sum=0;

        }
        return ans;

        }      

};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay