Answers for "find a subarray with maximum sum"

C#
2

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;
}
Posted by: Guest on September-09-2021
3

maximum sum subarray

public static int SumArray()
{
    var arr = new int[]{ -2, -4, -5, -6, -7, -89, -56 };
    var sum = 0;
    var max = arr[0];
    foreach (var item in arr)
    {
        sum += item;
      // sum = Math.Max(sum,0); resting here will not give  expected output
        max = Math.Max(sum,max);
        sum = Math.Max(sum,0);
    }
    return max;
}
Posted by: Guest on March-01-2022
3

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
0

maximum subarray

const maxSubArray = (arr) => {
    let currSum =  getSum(arr, 0, 4);
    let maxSum = 0
    for(let i = 1; i < arr.length - 4; i++){
       currSum =  currSum - arr[i - 1];
       currSum = currSum + arr[i + 3];
        maxSum = Math.max(currSum, maxSum);
    }
    return maxSum;
}

const getSum = (arr, start, end) => {
    let sum = 0;
    for(let i = start; i < end; i++){
        sum += arr[i]
    }
    
    console.log(sum);
    return sum;
}
Posted by: Guest on January-27-2022

C# Answers by Framework

Browse Popular Code Answers by Language