Skip to content

Commit

Permalink
- kaden's algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
DmytroYeremieiev committed Mar 15, 2023
1 parent d0f34e7 commit 6f730f4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,25 @@ def maxSubArray(arr: List[int]) -> int:
maxSumBest = -float('inf')
maxSumAtIndex = 0
s = 0
subArray = []
subArray = ()
for i in range(len(arr)):
maxSumAtIndex += arr[i]
if maxSumAtIndex > maxSumBest:
maxSumBest = maxSumAtIndex
subArray = [s, i]
if maxSumAtIndex < 0:
subArray = (s, i)
# Carrying a subArray which give you negative sum will be of no use because
# it will decrease your sum.
if maxSumAtIndex < 0:
maxSumAtIndex = 0
s = i + 1

return (maxSumBest, subArray)

def test(arr):
(longest, subArray) = maxSubArray(arr)
(longest, (start, end)) = maxSubArray(arr)
print(f"The longest subArray for {arr} with maximum sum is: ", longest)
print("The subArray is: ")
for i in range(subArray[0], subArray[1] + 1):
print(f"The subArray is: {(start, end)}")
for i in range(start, end + 1):
print(arr[i], end=" ")
print()

Expand Down
8 changes: 8 additions & 0 deletions src/Striver/arrays/kadane-algorithm(medium)/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,11 @@ Output: 1

Explanation: Array has only one element and which is giving positive sum of 1.
```

## Intuition

We carrying only a sub array which gives a positive sum, even if it contains negative numbers inside: `[4, -1, 2]`.

Carrying a subArray which give you negative sum will be of no use. Because you want to maximize the subArray sum. And carrying the negative sum will automatically decrease your sum.

If all elements are negative the greatest sum will come from a single smallest negative element. `start` and `end` indexes of such subArray will be equal.

0 comments on commit 6f730f4

Please sign in to comment.