find subarray sum code example

Example 1: 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

Example 2: how to find sum of array

//C++
int arr[5]={1,2,3,4,5};
int sum=0;
for(int i=0; i<5; i++){sum+=arr[i];}
cout<<sum;