Skip to content

Commit b6171f7

Browse files
added kadane's algorithm
1 parent e483259 commit b6171f7

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'''
2+
Kadane's Algorithm is a standard technique used majorly for problems like:
3+
4+
Given an integer array nums, find the contiguous subarray (containing at least one number)
5+
which has the largest sum and return its sum.
6+
'''
7+
def kadanes_algorithm(nums):
8+
max_ending_here = 0
9+
max_so_far = float('-inf')
10+
11+
for i in range(len(nums)):
12+
max_ending_here = max_ending_here+nums[i]
13+
max_so_far = max(max_so_far, max_ending_here)
14+
15+
if max_ending_here < 0:
16+
max_ending_here = 0
17+
18+
return max_so_far
19+
20+
nums = [-2,1,-3,4,-1,2,1,-5,4]
21+
print(kadanes_algorithm(nums)) # Output= 6
22+
23+
nums = [-1]
24+
print(kadanes_algorithm(nums)) #output= -1

0 commit comments

Comments
 (0)