Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kadane_algorithm #90

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Maximum Subarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Problem Statement

/*
Given an integer array nums, find the subarray with the largest sum, and return its sum.

*/

// Solution

#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0;
int maxi = nums[0];

for(int i = 0 ; i<nums.size() ; i++){
sum = sum + nums[i];

maxi = max(maxi , sum);

if(sum < 0)
sum = 0;
}
return maxi;
}
};



// Expected Output

/*
Test Case 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Test Case 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.
*/