Maximum Subarray
Problem
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.
Solution
Brute Force Algorithm
We sum all the elements between
Solution in C++
int maxSubArray(vector<int>& nums){
int maxSoFar = nums[0];
int sum;
for(int i = 0; i < nums.size(); ++i) {
sum = 0;
for(int j = i; j < nums.size(); ++j) {
sum = sum + nums[j];
maxSoFar = max(sum, maxSoFar);
}
}
return maxSoFar;
}
- Time complexity:
(where N is the size of the vector) - Space complexity:
Optimal Algorithm
This algorithm is called "Kadane's Algorithm"
Graphic explanation:
Solution in C++
int maxSubArray(vector<int>& nums){
int maxSoFar, maxHere;
maxSoFar = maxHere = nums[0];
for(int i = 1; i < nums.size(); ++i) {
maxHere = max(maxHere + nums[i], nums[i]);
maxSoFar = max(maxSoFar, maxHere);
}
return maxSoFar;
}
- Time complexity:
(where N is the size of the vector) - Space complexity: