2018-05-24

算法导论,分治算法,最大子数组问题。
python ,代码抄袭,Dacixie的博客
--
https://blog.csdn.net/Dacixie/article/details/79440014
(尊重作者,如果此处引用,您有意见,请联系我,qq 2466581516)

感谢 在线python 运行环境 ,
https://www.tutorialspoint.com/execute_python_online.php

def MaxCrossSubArray(A,low,mid,high):  
    LeftMaxSum=A[mid]  
    leftSum=A[mid]  
    leftIndex=mid  
    for i in range(mid-1,low-1,-1):  
        leftSum=leftSum+A[i]  
        if leftSum>LeftMaxSum:  
            LeftMaxSum=leftSum  
            leftIndex=i  
    rightMaxSum=0  
    rightSum=0  
    rightIndex=mid  
    for i in range(mid+1,high+1):  
        rightSum+=A[i]  
        if rightSum>rightMaxSum:  
            rightMaxSum=rightSum  
            rightIndex=i  
    MaxSum=LeftMaxSum+rightMaxSum  
    return [MaxSum,leftIndex,rightIndex] 
  
def MaxSubArray(A,low,high):  
    if low==high:  
        return [A[low],low,high]  
    mid=(low+high)//2  
    Left=MaxSubArray(A,low,mid)  
    Cross=MaxCrossSubArray(A,low,mid,high)  
    Right=MaxSubArray(A,mid+1,high)  
    List=[Left,Cross,Right]  
# there is some hard code,,,,,,,,, 
    result=sorted(List,key = lambda list : list[0],reverse=True)    
# only for see the detail ,,print   
 print result
    return result[0]  
  
a=[13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7,-99,88]  
print(MaxSubArray(a,0,len(a)-1)) 

the result

$python main.py
[[13, 0, 0], [13, 0, 0], [-3, 1, 1]]
[[13, 0, 0], [10, 0, 1], [-25, 2, 2]]
[[20, 3, 3], [20, 3, 3], [-3, 4, 4]]
[[20, 3, 3], [13, 0, 0], [5, 0, 3]]
[[-16, 5, 5], [-16, 5, 5], [-23, 6, 6]]
[[38, 7, 8], [20, 8, 8], [18, 7, 7]]
[[38, 7, 8], [15, 6, 8], [-16, 5, 5]]
[[38, 7, 8], [20, 3, 3], [17, 3, 4]]
[[12, 10, 10], [5, 9, 10], [-7, 9, 9]]
[[12, 10, 10], [12, 10, 10], [-5, 11, 11]]
[[15, 13, 13], [-7, 12, 13], [-22, 12, 12]]
[[15, 13, 13], [12, 10, 10], [7, 10, 11]]
[[7, 15, 15], [3, 14, 15], [-4, 14, 14]]
[[88, 17, 17], [-11, 16, 17], [-99, 16, 16]]
[[88, 17, 17], [7, 15, 15], [7, 15, 15]]
[[88, 17, 17], [18, 13, 15], [15, 13, 13]]
[[88, 17, 17], [43, 7, 10], [38, 7, 8]]
[88, 17, 17]

向下一山头 进发。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发起人:宝音道尔吉(Buyandorj) 蒙古国新能源发电公司 CEO 赛瑞德有限责任公司CEO 2009 年~2...
    周子茗阅读 3,496评论 0 0
  • MKT币全面介绍-夫子团队(官方节点代投对接团队) MKT注册链接: http://mkt.ffmex.com/r...
    豆豆是个迷阅读 1,720评论 0 1
  • mysql 优化数据库设计 第一范式(1st NF) 第一范式的目标是确保每列的原子性定义:数据库表中的所有字段都...
    xyxSUN阅读 3,017评论 0 1
  • 一片地动山摇之中,姬无尘和风逐云连忙稳住身形,震动逐渐停止。他们感到了一种危机感,姬无尘急忙对风逐云道:“这番地动...
    荣蔓蔓阅读 1,679评论 0 1
  • 第一封 早起,一缕阳光射进窗来,何时太阳竟升得这样早了,何时鸟儿叽喳得这样响了,躺在床上像躺在四方的天地里,伸手便...
    洛町田_阅读 2,629评论 0 0

友情链接更多精彩内容