Given an integer array
nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
class Solution:
def maxSubArray(self, nums):
dict1 = {}
for i in range(0, len(nums)):
for j in reversed(range(i, len(nums))):
dict1[(i, j+1)] = sum(nums[i:j+1])
maxvalue = max(dict1.values())
for key, value in dict1.items():
if value == maxvalue:
print(maxvalue)
return key
obj = Solution()
list1 = [-2,1,-3,4,-1,2,1,-5,4]
key = obj.maxSubArray(list1)
print(list1[key[0]:key[1]])
[4, -1, 2, 1]
Comments
Post a Comment