Skip to content

Commit 91f0395

Browse files
authored
Merge pull request #2 from ankana2113/kadane_algo
Kadane algo
2 parents 0c04372 + bfb8167 commit 91f0395

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

Diff for: data_structures/arrays/kadanes_algorithm.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Kadane's algorithm
2+
3+
4+
def kadanes_algorithm(arr: list[int]) -> int:
5+
"""
6+
Function to find the maximum sum of a contiguous subarray using Kadane's algorithm
7+
8+
>>> kadanes_algorithm([-2, 1, -3, 4, -1, 2, 1, -5, 4])
9+
6
10+
11+
>>> kadanes_algorithm([-1, -2, -3, -4])
12+
-1
13+
14+
>>> kadanes_algorithm([5, 4, -1, 7, 8])
15+
23
16+
17+
>>> kadanes_algorithm([1])
18+
1
19+
20+
>>> kadanes_algorithm([-1, 2, 3, -5, 4])
21+
5
22+
"""
23+
# initializing variables
24+
max_current = arr[0] # store the current max sum
25+
max_global = arr[0] # store the global max sum
26+
27+
# looping through the array starting at the second element
28+
for i in range(1, len(arr)):
29+
# update current max sum by choosing the maximum between
30+
# current element alone or current element plus previous max
31+
max_current = max(arr[i], max_current + arr[i])
32+
33+
# update global max sum if current max is larger
34+
max_global = max(max_current, max_global)
35+
36+
return max_global
37+
38+
39+
if __name__ == "__main__":
40+
import doctest
41+
42+
doctest.testmod()
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def largest_rectangle_area(heights: list[int]) -> int:
2+
"""
3+
Inputs an array of integers representing the heights of bars,
4+
and returns the area of the largest rectangle that can be formed
5+
6+
>>> largest_rectangle_area([2, 1, 5, 6, 2, 3])
7+
10
8+
9+
>>> largest_rectangle_area([2, 4])
10+
4
11+
12+
>>> largest_rectangle_area([6, 2, 5, 4, 5, 1, 6])
13+
12
14+
15+
>>> largest_rectangle_area([1])
16+
1
17+
"""
18+
stack: list[int] = []
19+
max_area = 0
20+
heights = [*heights, 0] # make a new list by appending the sentinel 0
21+
n = len(heights)
22+
23+
for i in range(n):
24+
# make sure the stack remains in increasing order
25+
while stack and heights[i] < heights[stack[-1]]:
26+
h = heights[stack.pop()] # height of the bar
27+
# if stack is empty, it means entire width can be taken from index 0 to i-1
28+
w = i if not stack else i - stack[-1] - 1 # calculate width
29+
max_area = max(max_area, h * w)
30+
31+
stack.append(i)
32+
33+
return max_area
34+
35+
36+
if __name__ == "__main__":
37+
import doctest
38+
39+
doctest.testmod()

0 commit comments

Comments
 (0)