-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path003. max subarray sum(lambda and map func)
More file actions
46 lines (37 loc) · 1.85 KB
/
003. max subarray sum(lambda and map func)
File metadata and controls
46 lines (37 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# accumulate culculate method
def max_subarray_sum(arr):
max_sum = arr[0]
current_sum = arr[0]
for i in arr[1:]:## start from the second element
current_sum = max(i, current_sum + i)## as long as the current_sum > 0, i + current_sum will large than i. So we can let the subarray accumulate until the sum is maximum
max_sum = max(current_sum, max_sum) ## after recording every turn of current_max, we will know which subarray is the largest one.
return max_sum
arr = [1, -2, 3, 4, -1, 2, 1, -5, 4]
result = max_subarray_sum(arr)
print("max subarray sum is:", result)
# My algorithm-use map function:
# The map function is used to convert each str generated by record.split() into int
# The map function is very convenient because it allows you to operate on the elements in an iterable object and generate a new resulting list without using an explicit loop.
# The map function is a very useful Python built-in function that allows you to apply a function to each element of an iterable object (such as a list, tuple, etc.), and then return a new iterable object containing The result of function processing.
def subarray():
record = input()
record_list = list(map(int, record.split()))
record_sum = int(record_list[0])
record_total = int(record_list[0])
for i in record_list[1:]:
record_sum = max(i, record_sum + i)
record_total = max(record_sum, record_total)
return record_total
# My force resolution:
def max_subarray_sum_bruteforce(arr):
max_sum = float('-inf')
for i in range(len(arr)):
current_sum = 0
for j in range(i, len(arr)):
current_sum += arr[j]
max_sum = max(max_sum, current_sum)
return max_sum
arr = [1, -2, 3, 4, -1, 2, 1, -5, 4]
result = max_subarray_sum_bruteforce(arr)
print("Maximum subarray sum (Brute Force):", result)
subarray()