Answers for "largest sub array sum"

C++
2

kadane algorithm

public int kadane(int[] arr){
	int max_so_far = 0, curr_max = Integer.MIN_VALUE;
    for(int i: arr){
    	max_so_far += i;
        if(max_so_far<0) max_so_far = 0;
        if(max_so_far>curr_max) curr_max = max_so_far;
    }
    return curr_max;
}
Posted by: Guest on June-20-2020
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
Posted by: Guest on February-26-2020
-2

largest subarray of sum k

//variable size sliding window
#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    cout<<"Enter the size of the array:"<<endl;
    cin>>n;
    int arr[n];
    cout<<"Enter the elements of the array:"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    int k;
    cout<<"enter the sum whose longest subarray you want to find:"<<endl;
    cin>>k;
    int i=0,j=0,sum=0;
    int mx=0;
    while(j<n)
    {
        sum=sum+arr[j];
        if(sum<k)
        {
            j++;
        }
        else if(sum==k)
        {
            mx=max(mx,j-i+1);
            j++;
        }
        else
        {
            while(sum>k)
            {
                sum=sum-arr[i];
                i++;
            }
            j++;
        }
    }
    cout<<mx<<endl;
    return 0;
}
Posted by: Guest on June-24-2021

Browse Popular Code Answers by Language