|
| 1 | + |
| 2 | + |
| 3 | +""" |
| 4 | +Time Complexity: O(NLogN) |
| 5 | +Space Complexity: O(N) ( Reason: Recursive stack pointer for every element ) |
| 6 | +
|
| 7 | +Divide and Conquer Approach |
| 8 | +
|
| 9 | +1. Divide the array into two halves |
| 10 | +2. Find the maximum subarray sum in the left half |
| 11 | +3. Find the maximum subarray sum in the right half |
| 12 | +4. Find the maximum subarray sum that crosses the midpoint |
| 13 | +5. Return the maximum of the three sums |
| 14 | +""" |
| 15 | +# class Solution: |
| 16 | +# def maxSubArray(self, nums: List[int]) -> int: |
| 17 | + |
| 18 | +# def divide(start: int, end: int) -> int: |
| 19 | +# if start >= end: |
| 20 | +# return nums[start] |
| 21 | + |
| 22 | +# mid = (start + end) // 2 |
| 23 | + |
| 24 | +# left = divide(start, mid) |
| 25 | +# right = divide(mid + 1, end) |
| 26 | + |
| 27 | +# left_largest = -float('inf') |
| 28 | +# right_largest = -float('inf') |
| 29 | + |
| 30 | +# left_acc = 0 |
| 31 | +# right_acc = 0 |
| 32 | + |
| 33 | +# left_index = mid |
| 34 | +# right_index = mid + 1 |
| 35 | + |
| 36 | +# while left_index >= start: |
| 37 | +# left_acc += nums[left_index] |
| 38 | +# left_largest = max(left_largest, left_acc) |
| 39 | +# left_index -= 1 |
| 40 | + |
| 41 | +# while right_index <= end: |
| 42 | +# right_acc += nums[right_index] |
| 43 | +# right_largest = max(right_largest, right_acc) |
| 44 | +# right_index += 1 |
| 45 | + |
| 46 | +# return max(left_largest + right_largest, left, right) |
| 47 | + |
| 48 | +# return divide(0, len(nums) - 1) |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +""" |
| 54 | +Time Complexity: O(N) |
| 55 | +Space Complexity: O(1) |
| 56 | +
|
| 57 | +prev : maximum sum of the subarray ending with the previous element |
| 58 | +ans : maximum sum of the subarray |
| 59 | +curr : maximum sum of the subarray ending with the current element |
| 60 | +""" |
| 61 | +class Solution: |
| 62 | + def maxSubArray(self, nums: List[int]) -> int: |
| 63 | + N = len(nums) |
| 64 | + prev = nums[0] |
| 65 | + ans = nums[0] |
| 66 | + |
| 67 | + for i in range(1, N): |
| 68 | + prev = max(nums[i], prev + nums[i]) |
| 69 | + ans = max(ans, prev) |
| 70 | + |
| 71 | + return ans |
0 commit comments