📜  具有最大和的子数组大小的 Python3 程序

📅  最后修改于: 2022-05-13 01:54:24.756000             🧑  作者: Mango

具有最大和的子数组大小的 Python3 程序

给定一个数组,找出总和最大的子数组的长度。

例子 :

Input :  a[] = {1, -2, 1, 1, -2, 1}
Output : Length of the subarray is 2
Explanation: Subarray with consecutive elements 
and maximum sum will be {1, 1}. So length is 2

Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }
Output : Length of the subarray is 5
Explanation: Subarray with consecutive elements 
and maximum sum will be {4, -1, -2, 1, 5}. 

这个问题主要是最大和连续子数组问题的变体。
这个想法是每当此处结束的总和小于 0 时更新起始索引。

Python3
# Python3 program to print largest contiguous array sum
  
from sys import maxsize
  
# Function to find the maximum contiguous subarray
# and print its starting and end index
def maxSubArraySum(a,size):
  
    max_so_far = -maxsize - 1
    max_ending_here = 0
    start = 0
    end = 0
    s = 0
  
    for i in range(0,size):
  
        max_ending_here += a[i]
  
        if max_so_far < max_ending_here:
            max_so_far = max_ending_here
            start = s
            end = i
  
        if max_ending_here < 0:
            max_ending_here = 0
            s = i+1
  
    return (end - start + 1)
  
# Driver program to test maxSubArraySum
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print(maxSubArraySum(a,len(a)))


输出 :
5

有关更多详细信息,请参阅有关具有最大总和的子数组的大小的完整文章!