Skip to content

Commit 793e564

Browse files
authored
Create maximum_subsequence.py (TheAlgorithms#7811)
1 parent 6939538 commit 793e564

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Diff for: DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,7 @@
716716
* [Lru Cache](other/lru_cache.py)
717717
* [Magicdiamondpattern](other/magicdiamondpattern.py)
718718
* [Maximum Subarray](other/maximum_subarray.py)
719+
* [Maximum Subsequence](other/maximum_subsequence.py)
719720
* [Nested Brackets](other/nested_brackets.py)
720721
* [Password](other/password.py)
721722
* [Quine](other/quine.py)

Diff for: other/maximum_subsequence.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from collections.abc import Sequence
2+
3+
4+
def max_subsequence_sum(nums: Sequence[int] | None = None) -> int:
5+
"""Return the maximum possible sum amongst all non - empty subsequences.
6+
7+
Raises:
8+
ValueError: when nums is empty.
9+
10+
>>> max_subsequence_sum([1,2,3,4,-2])
11+
10
12+
>>> max_subsequence_sum([-2, -3, -1, -4, -6])
13+
-1
14+
>>> max_subsequence_sum([])
15+
Traceback (most recent call last):
16+
. . .
17+
ValueError: Input sequence should not be empty
18+
>>> max_subsequence_sum()
19+
Traceback (most recent call last):
20+
. . .
21+
ValueError: Input sequence should not be empty
22+
"""
23+
if nums is None or not nums:
24+
raise ValueError("Input sequence should not be empty")
25+
26+
ans = nums[0]
27+
for i in range(1, len(nums)):
28+
num = nums[i]
29+
ans = max(ans, ans + num, num)
30+
31+
return ans
32+
33+
34+
if __name__ == "__main__":
35+
import doctest
36+
37+
doctest.testmod()
38+
39+
# Try on a sample input from the user
40+
n = int(input("Enter number of elements : ").strip())
41+
array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
42+
print(max_subsequence_sum(array))

0 commit comments

Comments
 (0)