码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - The Maximum Subarray

时间:2015-03-03 16:34:35      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

Point: not necessarily contigous max sub array, at least one element should be selected:

def maxSubarrCont(arr, n):
    ret = arr[0]
    curr = arr[0]
    for i in range(1, n):
        curr = max(arr[i], curr + arr[i])
        ret = max(ret, curr)    
    return ret

def maxSubarrNoCont(arr, n):    
    #    Corner case: no empty ret is allowed
    cnt = 0
    neg_max = -100001
    #
    ret = 0
    for i in range(0, n):
        d = max(0, arr[i])
        ret += d
        if d > 0: cnt += 1
        if arr[i] < 0:
            neg_max = max(neg_max, arr[i])
    if cnt == 0:
        return neg_max    
    return ret
    
T = input()
for i in xrange(T):
    N = int(input())
    arr = map(int, raw_input().split())
    print maxSubarrCont(arr, N), maxSubarrNoCont(arr, N)

HackerRank - The Maximum Subarray

标签:

原文地址:http://www.cnblogs.com/tonix/p/4311271.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!