本文概述
- python
- python
文章图片
python
# Python program to find maximum contiguous subarray# Function to find the maximum contiguous subarray
from sys import maxint
def maxSubArraySum(a, size):max_so_far = - maxint - 1
max_ending_here = 0for i in range ( 0 , size):
max_ending_here = max_ending_here + a[i]
if (max_so_far <
max_ending_here):
max_so_far = max_ending_hereif max_ending_here <
0 :
max_ending_here = 0
return max_so_far# Driver function to check the above function
a = [ - 13 , - 3 , - 25 , - 20 , - 3 , - 16 , - 23 , - 12 , - 5 , - 22 , - 15 , - 4 , - 7 ]
print "Maximum contiguous sum is" , maxSubArraySum(a, len (a))# This code is contributed by _Devesh Agrawal_
输出如下:
Maximum contiguous sum is -3
如果我们将max_so_far与max_ending_here进行比较, 则仅当max_ending_here大于0时, 才能进一步优化上述程序。
python
def maxSubArraySum(a, size):max_so_far = 0
max_ending_here = 0for i in range ( 0 , size):
max_ending_here = max_ending_here + a[i]
if max_ending_here <
0 :
max_ending_here = 0# Do not compare for all elements. Compare only
# whenmax_ending_here>
0
elif (max_so_far <
max_ending_here):
max_so_far = max_ending_herereturn max_so_far
【最大和连续子数组的Python程序】请参考完整的文章最大总和连续子数组更多细节!
推荐阅读
- 查找奇数次出现的数字的Python程序
- 数学建模|【建模算法】基于模拟退火算法求解TSP问题(Python实现)
- 数学建模|【建模算法】Python调用scikit-opt工具箱中的模拟退火算法求解TSP问题
- 程序员|Python爬虫系列(爬取小说并写入txt文件)
- Python|模拟退火算法解决TSP(python实现 110+行代码)【gif生成】
- 启发式算法|模拟退火算法求解 TSP 问题的代码示例
- #yyds干货盘点# Python训练营Python每日一练----第23天:字符计数
- #yyds干货盘点# Kubernetes helm 如何在生产环境中释放部署生产力((12))
- #yyds干货盘点# Kotlin随查指南,妈妈再也不担心我不会Ctrl+F了