Skip to content

Commit

Permalink
Add test cases for max subarray (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
Diego committed Dec 4, 2021
1 parent 6a4df44 commit 6d59876
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
12 changes: 1 addition & 11 deletions sols/python/code_challenges/arrays/two_pointers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,6 @@ class MaxSubarrayDivideAndConquer:
def cross_sum(self, nums: List[int], low: int, high: int, mid: int) -> int:
"""Compute the maximum sum of a subarray passing through the middle.
Input: nums = [5,4,-1,7,8]
Output: 23
Input: nums = [1]
Output: 1
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
This is ``O(n)`` in complexity.
:param nums: List of numbers
Expand Down Expand Up @@ -72,7 +62,7 @@ def divide_and_conquer(self, nums: List[int], low: int, high: int) -> int:
cross_sum = self.cross_sum(nums, low, high, mid)
return max(left_sum, right_sum, cross_sum)

def maxSubArray(self, nums: List[int]) -> int:
def max_sub_array(self, nums: List[int]) -> int:
"""Implement a divide and conquer solution.
This algorithm is ``O(nlog(n))`` and it is based on the idea of
Expand Down
31 changes: 30 additions & 1 deletion sols/python/tests/arrays/test_two_pointers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
"""Test cases for two_pointers."""
from code_challenges.arrays.two_pointers import rotate_naive, rotate_mem_opt
from code_challenges.arrays.two_pointers import (
rotate_naive,
rotate_mem_opt,
MaxSubarrayDivideAndConquer,
max_sub_array_sum,
)


def test_sample_cases():
Expand Down Expand Up @@ -48,3 +53,27 @@ def test_360_and_k_rotation():
k = len(nums) + 3
rotate_mem_opt(nums, k)
assert nums == [5, 6, 7, 1, 2, 3, 4]


def test_max_subarray_sum():
"""Simple test cases for max subarray sum."""
nums = [5, 4, -1, 7, 8]
assert (
MaxSubarrayDivideAndConquer().max_sub_array(nums)
== 23
== max_sub_array_sum(nums)
)

nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
assert (
MaxSubarrayDivideAndConquer().max_sub_array(nums)
== 6
== max_sub_array_sum(nums)
)

nums = [1]
assert (
MaxSubarrayDivideAndConquer().max_sub_array(nums)
== 1
== max_sub_array_sum(nums)
)

0 comments on commit 6d59876

Please sign in to comment.