Time Limit Exceeded

I’m getting a time limit error for this problem ===> https://leetcode.com/problems/maximum-subarray/

Any Ideas on how I can save time? This code has passed 199/202 test cases

Here is the problem:
Given an integer array nums , find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.


Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.

Here is my solution

    def maxSubArray(self, nums: List[int]) -> int:
        x = 0
        y = None
        for i in range(len(nums)):
            for j in range(len(nums)-1 , i -1, -1):
                for k in range(j, i - 1, -1):
                    x += nums[k]
                if y == None:
                    y = x
                if x > y:
                    y = x
                x = 0
        return y

You can do that in a single pass (and if you do it manually you’re likely to discover how, because as a human you’re a just-in-time optimizer)

Do what manually? I want to do something manually

“it” being the task your program is supposed to solve

1 Like

I’m trying to wrap my head around it. It has something to do with large streaks of negative numbers ending the positive streaks. I cant formulate it better than that at the moment.