Horje
find maximum sum in array of contiguous subarrays Code Example
find maximum sum in array of contiguous subarrays
#include <iostream>

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;
}
find longest subarray by sum
def max_length(s, k):
    current = []
    max_len = -1 # returns -1 if there is no subsequence that adds up to k.
    for i in s:
        current.append(i)
        while sum(current) > k: # Shrink the array from the left, until the sum is <= k.
           current = current[1:]
        if sum(current) == k:
            max_len = max(max_len, len(current))

    return max_len




Cpp

Related
char to int in c++ Code Example char to int in c++ Code Example
program to swap max and min in matrix Code Example program to swap max and min in matrix Code Example
c++ looping through a vector Code Example c++ looping through a vector Code Example
remove from vector by value c++ Code Example remove from vector by value c++ Code Example
compile in c++ Code Example compile in c++ Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
12