53. Maximum Subarray
O(n)
import sys
from typing import List

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        m = -sys.maxsize-1 # global max value
        mt = 0 # sub array max value

        for i in range(len(nums)):
            mt += nums[i]
            if mt > m:
                m = mt
            if mt < 0:
                mt = 0
            #print(i, mt, m, nums[i])
        return m

def main():
    s = Solution()

    print(s.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
    print(s.maxSubArray([-1]))

if __name__ == '__main__':
    main()
			
Reference
  • Geeksforgeeks