八. Array 1 Maximum Subarray

八. Array 1 Maximum Subarray_第1张图片

Idea:

  1. Brute force ----- O(n^2)
  2. Kadane's Algorithm (always looking for the Maximum Subarray of sums[i] which ending with itself and Comparing the largest value of every sums[i] to obtain the maximum value) ----- O(n)
  1. Brute Force
class Solution:
    """
    @param nums: A list of integers
    @return: A integer indicate the sum of max subarray
    """
    def maxSubArray(self, nums):
        # write your code here
        
        subarray_sum = -float("inf")
        for i in range(0, len(nums)):
            sum = nums[i]
            if sum > subarray_sum:
                subarray_sum = sum
            if sum < 0:
                continue
            for n in range(i+1, len(nums)):
                sum +=nums[n]
                if sum > 0:
                    if sum > subarray_sum:
                        subarray_sum = sum
                else:
                    break
                
        return subarray_sum
  1. Kadane's Algorithm
class Solution:
    """
    @param nums: A list of integers
    @return: A integer indicate the sum of max subarray
    """
    def maxSubArray(self, nums):
        # write your code here
        previous = nums[0]
        nums.pop(0)
        max =previous
        for node in nums:
            if previous + node > node:
                previous += node
            else:
                previous = node
            if max < previous:
                max = previous
        return max

你可能感兴趣的:(八. Array 1 Maximum Subarray)