Skip to content

Commit 528b129

Browse files
pronoym99Cjkjvfnbypre-commit-ci[bot]
authored
Update maximum_subarray.py (#7757)
* Update maximum_subarray.py 1. Rectify documentation to indicate the correct output: function doesn't return the subarray, but rather returns a sum. 2. Make the function more Pythonic and optimal. 3. Make function annotation generic i.e. can accept any sequence. 4. Raise value error when the input sequence is empty. * Update maximum_subarray.py 1. Use the conventions as mentioned in pep-0257. 2. Use negative infinity as the initial value for the current maximum and the answer. * Update maximum_subarray.py Avoid type conflict by returning the answer cast to an integer. * Update other/maximum_subarray.py Co-authored-by: Andrey <[email protected]> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update maximum_subarray.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update maximum_subarray.py Remove typecast to int for the final answer Co-authored-by: Andrey <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent d9efd7e commit 528b129

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

Diff for: other/maximum_subarray.py

+18-12
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,26 @@
1-
def max_subarray(nums: list[int]) -> int:
2-
"""
3-
Returns the subarray with maximum sum
4-
>>> max_subarray([1,2,3,4,-2])
1+
from collections.abc import Sequence
2+
3+
4+
def max_subarray_sum(nums: Sequence[int]) -> int:
5+
"""Return the maximum possible sum amongst all non - empty subarrays.
6+
7+
Raises:
8+
ValueError: when nums is empty.
9+
10+
>>> max_subarray_sum([1,2,3,4,-2])
511
10
6-
>>> max_subarray([-2,1,-3,4,-1,2,1,-5,4])
12+
>>> max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4])
713
6
814
"""
15+
if not nums:
16+
raise ValueError("Input sequence should not be empty")
917

1018
curr_max = ans = nums[0]
19+
nums_len = len(nums)
1120

12-
for i in range(1, len(nums)):
13-
if curr_max >= 0:
14-
curr_max = curr_max + nums[i]
15-
else:
16-
curr_max = nums[i]
17-
21+
for i in range(1, nums_len):
22+
num = nums[i]
23+
curr_max = max(curr_max + num, num)
1824
ans = max(curr_max, ans)
1925

2026
return ans
@@ -23,4 +29,4 @@ def max_subarray(nums: list[int]) -> int:
2329
if __name__ == "__main__":
2430
n = int(input("Enter number of elements : ").strip())
2531
array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
26-
print(max_subarray(array))
32+
print(max_subarray_sum(array))

0 commit comments

Comments
 (0)