From 530c42430a885bfe37e865fae265c2a7db1c04f6 Mon Sep 17 00:00:00 2001 From: Pronoy Mandal Date: Fri, 28 Oct 2022 22:21:53 +0530 Subject: [PATCH] Create maximum_subsequence.py --- other/maximum_subsequence.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 other/maximum_subsequence.py diff --git a/other/maximum_subsequence.py b/other/maximum_subsequence.py new file mode 100644 index 000000000000..26488dd7211c --- /dev/null +++ b/other/maximum_subsequence.py @@ -0,0 +1,31 @@ +from collections.abc import Sequence + + +def max_subsequence_sum(nums: Sequence[int]) -> int: + """Return the maximum possible sum amongst all non - empty subsequences. + + Raises: + ValueError: when nums is empty. + + >>> max_subsequence_sum([1,2,3,4,-2]) + 10 + >>> max_subsequence_sum([-2, -3, -1, -4, -6]) + -1 + """ + if not nums: + raise ValueError("Input sequence should not be empty") + + ans = nums[0] + nums_len = len(nums) + + for i in range(1, nums_len): + num = nums[i] + ans = max(ans, ans + num, num) + + return ans + + +if __name__ == "__main__": + n = int(input("Enter number of elements : ").strip()) + array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] + print(max_subsequence_sum(array))