Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0f56ab5

Browse files
Dharni0607Erfaniaa
authored andcommitted
Divide and conquer Algorithms Issue#817 (#938)
* add ons in string directory - Bayer_Moore_Search* created divide_and_conquer folder and added max_sub_array_sum.py under it (issue #817)
1 parent27a8184 commit0f56ab5

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
Given a array of length n, max_sub_array_sum() finds the maximum of sum of contiguous sub-array using divide and conquer method.
3+
4+
Time complexity : O(n log n)
5+
6+
Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION (section : 4, sub-section : 4.1, page : 70)
7+
8+
"""
9+
10+
11+
defmax_sum_from_start(array):
12+
""" This function finds the maximum contiguous sum of array from 0 index
13+
14+
Parameters :
15+
array (list[int]) : given array
16+
17+
Returns :
18+
max_sum (int) : maximum contiguous sum of array from 0 index
19+
20+
"""
21+
array_sum=0
22+
max_sum=float("-inf")
23+
fornuminarray:
24+
array_sum+=num
25+
ifarray_sum>max_sum:
26+
max_sum=array_sum
27+
returnmax_sum
28+
29+
30+
defmax_cross_array_sum(array,left,mid,right):
31+
""" This function finds the maximum contiguous sum of left and right arrays
32+
33+
Parameters :
34+
array, left, mid, right (list[int], int, int, int)
35+
36+
Returns :
37+
(int) : maximum of sum of contiguous sum of left and right arrays
38+
39+
"""
40+
41+
max_sum_of_left=max_sum_from_start(array[left:mid+1][::-1])
42+
max_sum_of_right=max_sum_from_start(array[mid+1:right+1])
43+
returnmax_sum_of_left+max_sum_of_right
44+
45+
46+
defmax_sub_array_sum(array,left,right):
47+
""" This function finds the maximum of sum of contiguous sub-array using divide and conquer method
48+
49+
Parameters :
50+
array, left, right (list[int], int, int) : given array, current left index and current right index
51+
52+
Returns :
53+
int : maximum of sum of contiguous sub-array
54+
55+
"""
56+
57+
# base case: array has only one element
58+
ifleft==right:
59+
returnarray[right]
60+
61+
# Recursion
62+
mid= (left+right)//2
63+
left_half_sum=max_sub_array_sum(array,left,mid)
64+
right_half_sum=max_sub_array_sum(array,mid+1,right)
65+
cross_sum=max_cross_array_sum(array,left,mid,right)
66+
returnmax(left_half_sum,right_half_sum,cross_sum)
67+
68+
69+
array= [-2,-5,6,-2,-3,1,5,-6]
70+
array_length=len(array)
71+
print("Maximum sum of contiguous subarray:",max_sub_array_sum(array,0,array_length-1))
72+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp