find maximum sum in array of contiguous subarrays 1

find maximum sum in array of contiguous subarrays

#include 

using namespace std;

int main(){
    //Input Array
    int n;
    cin >> n;
    int arr[n];
    for(int i =0;i< n;i++){
    cin >> arr[i];
    }

    int currentSum = 0;
    int maxSum = INT_MIN;
    //algo
    for (int i = 0; i < n; i++)
    {
        currentSum += arr[i];
        if (currentSum <0)
        {
            currentSum = 0;
        }
        maxSum = max(maxSum, currentSum);
    }
    cout << maxSum << endl;

    return 0;
}

Here is what the above code is Doing:
1. We are taking the input array and storing it in arr[].
2. We are initializing currentSum = 0 and maxSum = INT_MIN.
3. We are iterating over the array and adding the current element to currentSum.
4. If currentSum becomes negative, we reset it to 0.
5. We update maxSum if it is less than currentSum.
6. We print maxSum.

Similar Posts