diff --git a/data_structures/arrays/kadanes_algorithm.py b/data_structures/arrays/kadanes_algorithm.py new file mode 100644 index 000000000000..2650d6a7e03a --- /dev/null +++ b/data_structures/arrays/kadanes_algorithm.py @@ -0,0 +1,30 @@ +"""Given an integer array nums, find the subarray with the largest sum, and return its sum. +Example 1: +Input: nums = [-2,1,-3,4,-1,2,1,-5,4] +Output: 6 +Explanation: The subarray [4,-1,2,1] has the largest sum 6. +Example 2: +Input: nums = [1] +Output: 1 +Explanation: The subarray [1] has the largest sum 1. +Example 3: +Input: nums = [5,4,-1,7,8] +Output: 23 +Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. +""" + + +def max_subArray(self, nums: List[int]) -> int: + # kadane's algorithm# + curr = 0 + maxtillnow = -inf + for c in nums: + curr = max(c, curr + c) + maxtillnow = max(curr, maxtillnow) + return maxtillnow + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/other/two_sum_advance.py b/other/two_sum_advance.py new file mode 100644 index 000000000000..52f3fe3cc463 --- /dev/null +++ b/other/two_sum_advance.py @@ -0,0 +1,43 @@ +"""Pointer Solution +Example 1: + +Input: numbers = [2,7,11,15], target = 9 +Output: [1,2] +Explanation: The sum of 2 and 7 is 9. +Therefore, index1 = 1, index2 = 2. We return [1, 2]. +Example 2: + +Input: numbers = [2,3,4], target = 6 +Output: [1,3] +Explanation: The sum of 2 and 4 is 6. +Therefore index1 = 1, index2 = 3. We return [1, 3]. +Example 3: + +Input: numbers = [-1,0], target = -1 +Output: [1,2] +Explanation: The sum of -1 and 0 is -1. +Therefore index1 = 1, index2 = 2. We return [1, 2]. +""" + + +def two_sum(self, numbers: list[int], target: int) -> list[int]: + n = len(numbers) + l = 0 + r = n - 1 + res = [] + while l < r: + if numbers[l] + numbers[r] == target: + res.append(l + 1) + res.append(r + 1) + if numbers[l] + numbers[r] > target: + r -= 1 + else: + l += 1 + res.sort() + return res + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/requirements.txt b/requirements.txt index acfbc823e77f..2702523d542e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,6 +9,7 @@ pandas pillow projectq qiskit +qiskit-aer requests rich scikit-fuzzy