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 array nums.
  • currentSum variable is also initialized with the first element of the input array nums.
  • The for loop starts from index 1 and iterates through the input array nums.
  • Within the loop, currentSum is updated using the maximum between the current element nums[i] and the sum of the current element and the previous currentSum.
  • maxSum is updated using the maximum between the current maxSum and the updated currentSum.
  • Finally, the function returns maxSum.

  • In the main function, a test array arr is created.

  • maxSubArray function is called with arr as an argument, and the result is stored in the result variable.
  • The maximum sum of a subarray (result) is displayed to the console.