Skip to content

Commit 590b729

Browse files
Create max_subarray_sum_length4.py
1 parent 42cc9ce commit 590b729

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

max_subarray_sum_length4.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# max_subarray_sum_length4.py
2+
# ------------------------------------
3+
# Program to generate all subarrays of a list
4+
# and find the maximum sum among subarrays of length 4.
5+
#
6+
# Time Complexity: O(n^3)
7+
# Space Complexity: O(n^2)
8+
# ------------------------------------
9+
10+
# Input array
11+
n = [5, 9, 1, 8, 7]
12+
13+
# Variables for maximum sum (m) and temporary sum (s)
14+
m = 0
15+
s = 0
16+
17+
# To store all possible subarrays
18+
ans = []
19+
20+
# Generate all subarrays
21+
for i in range(len(n)): # Start index
22+
for j in range(i, len(n)): # End index
23+
temp = []
24+
for k in range(i, j + 1): # Collect elements from i to j
25+
temp.append(n[k])
26+
ans.append(temp) # Add subarray to ans list
27+
28+
# Print all subarrays
29+
print("All subarrays:")
30+
print(ans)
31+
32+
# Check subarrays of length 4 and calculate their sums
33+
print("\nSubarrays of length 4 and their sums:")
34+
for i in range(len(ans)):
35+
if len(ans[i]) == 4: # Only consider subarrays of length 4
36+
s = sum(ans[i]) # Calculate sum
37+
m = max(m, s) # Update maximum sum
38+
print(ans[i], "Max so far:", m, "Sum:", s)
39+
40+
# Final maximum sum among subarrays of length 4
41+
print("\nMaximum sum among subarrays of length 4:", m)

0 commit comments

Comments
 (0)