
Idea:
- Brute force ----- O(n^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)
- 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
- 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
网友评论