maximum sum subarray
#include<iostream>
#include<vector>
using namespace std;
int maxSubArray(vector<int>& nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.size(); i++) {
currentSum = max(nums[i], currentSum + nums[i]);
maxSum = max(maxSum, currentSum);
}
return maxSum;
}
int main() {
vector<int> arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
int result = maxSubArray(arr);
cout << "Maximum sum of a subarray: " << result << endl;
return 0;
}
Explanation:
maxSubArray
function takes a vector of integers (nums
) as input and returns an integer.maxSum
variable is initialized with the first element of the input arraynums
.currentSum
variable is also initialized with the first element of the input arraynums
.- The
for
loop starts from index 1 and iterates through the input arraynums
. - Within the loop,
currentSum
is updated using the maximum between the current elementnums[i]
and the sum of the current element and the previouscurrentSum
. maxSum
is updated using the maximum between the currentmaxSum
and the updatedcurrentSum
.Finally, the function returns
maxSum
.In the
main
function, a test arrayarr
is created.maxSubArray
function is called witharr
as an argument, and the result is stored in theresult
variable.- The maximum sum of a subarray (
result
) is displayed to the console.