Answers for "maximum subarray solution"

C#
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
5

max subsequence sum in array

def max_subarray(numbers):
    """Find the largest sum of any contiguous subarray."""
    best_sum = 0  # or: float('-inf')
    current_sum = 0
    for x in numbers:
        current_sum = max(0, current_sum + x)
        best_sum = max(best_sum, current_sum)
    return best_sum
Posted by: Guest on September-14-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