Maximum Subarray Leetcode Python

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.


For example, given the array [−2,1,−3,4,−1,2,1,−5,4],

the contiguous subarray [4,−1,2,1] has the largest sum = 6.

这题可以用三种方法来解。

第一种最容易想到的是 brute force的方法,把整个array循环两边。得到最大值。

这里空间O(1)

 时间O(n^2)

def brutef(arr):
    maxval=-10000
    
    for i in range(len(arr)):
        for j in range(i,len(arr)):
            if maxval<sum(arr[i:j]):
                print i,j
                maxval=max(maxval,sum(arr[i:j]))
                result=arr[i:j]
    


第二种借用mergesort的思想,将整个array依次往下分分别向左向右找最大,最后将最大的合并。

因为每次都要分两边,所以时间复杂度是O(nlog)

先定义一个函数是 dividecon 用来求每步最优

def dividecon(num,low,mid,high):
    #calculate left
    lowsum=-10000
    cursum=num[low]
    left=low
    for index in reversed(range(low,mid)):
        cursum+=num[index]
        if cursum>lowsum:
            lowsum=cursum
            left=index
    highsum=-10000
    cursum=0
    right=high
    for index in range(mid+1,high):
        cursum+=num[index]
        if cursum>highsum:
            highsum=cursum
            right=index
    return [left,right,lowsum+highsum]
再在 主函数里面调用这个函数。

def findsub(A,low,high):
    if high==low:
        return [low,high,A[low]]
    else:
        mid=low+(high-low)/2
        [leftlow,lefthigh,leftsum]=findsub(A,low,mid)
        [rightlow,righthigh,rightsum]=findsub(A,mid+1,high)
        [crosslow,crosshigh,crosssum]=dividecon(A,low,mid,high)

        if leftsum>=rightsum and leftsum>=crosssum:
            return [leftlow,lefthigh,leftsum]
        if rightsum>=leftsum and rightsum>=crosssum:
            return [rightlow,righthigh,rightsum]
        else:
            return [crosslow,crosshigh,crosssum]
依次比较如果最大都在左边,那就返回左边的值,如果最大都在右边那就返回右边的值,否则两者有交叉就返回cross的值

还要一种方法是时间O(n)空间 O(1)

做法就是把整个array扫描一遍记录下当前最大值,如果得到的当前值小于0就将其置0,最后可以得到答案


def findmax(arr):
    cursum=0
    maxval=arr[0]
    for index in range(len(arr)):
        if cursum<0:
            cursum=0
        cursum+=arr[index]
        maxval=max(maxval,cursum)




你可能感兴趣的:(LeetCode,array,python)