Answers for "how to find the maximum subarray sum in python?"

C#
1

Maximum Subarray sum

def maxSubArray(self, nums: List[int]) -> int:
        curr_best = overall_best =  nums[0]
        for i in range(1,len(nums)):
            if curr_best>=0:
                curr_best = curr_best + nums[i]
            else:
                curr_best = nums[i]
            if curr_best > overall_best:
                overall_best = curr_best
        return overall_best
Posted by: Guest on May-20-2022
1

How to find the maximum subarray sum in python?

"""
Implementation of "kadane's algorithm".
It returns the maximum subarray sum for
a given bigger array.
Time complexity: O(n)
Space complexity: O(1)
"""

def kadane_algorithm(array):
    running_sum = array[0]
    max_sum = array[0]
    for idx in range(1, len(array)):
        current_val = array[idx]
        running_sum = max(current_val, running_sum+current_val)
        max_sum = max(max_sum, running_sum)
    return max_sum

print(kadane_algorithm([1, 2, 3, 5, -1]))  # 11 = 1 + 2 + 3 + 5
Posted by: Guest on May-03-2022
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
0

print maximum sum subarray

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n;
	cin>>n;
	int a[n];
	for(int  i = 0;i<n;i++){
		cin>>a[i];
	}
	int s = 0;
	int mx = INT_MIN;
	for(int  i =0;i<n;i++){
		s+=a[i];
		if(s<0){
			s=0;
		}
		mx = max(s,mx);
	}
	cout<<mx;
	return 0;
}
Posted by: Guest on January-24-2022

Code answers related to "how to find the maximum subarray sum in python?"

C# Answers by Framework

Browse Popular Code Answers by Language