Остання активність 1731081431

Версія 4eb2c7bdda3d69585d9e41d69868171274a654e4

getminSum.py Неформатований
1
2def getMinimumSum(arr):
3 n = len(arr)
4 if n < 3:
5 return -1
6
7 left_min = [None] * n
8 min_so_far = float('inf')
9
10 # Populate left_min
11 for j in range(n):
12 if min_so_far < arr[j]:
13 left_min[j] = min_so_far
14 else:
15 left_min[j] = None
16 if arr[j] < min_so_far:
17 min_so_far = arr[j]
18
19 right_min = [None] * n
20 min_so_far = float('inf')
21
22 # Populate right_min
23 for j in range(n-1, -1, -1):
24 if min_so_far < arr[j]:
25 right_min[j] = min_so_far
26 else:
27 right_min[j] = None
28 if arr[j] < min_so_far:
29 min_so_far = arr[j]
30
31 min_sum = float('inf')
32 for j in range(n):
33 if left_min[j] is not None and right_min[j] is not None:
34 current_sum = left_min[j] + arr[j] + right_min[j]
35 if current_sum < min_sum:
36 min_sum = current_sum
37
38 return min_sum if min_sum != float('inf') else -1
39
40# Example Usage:
41if __name__ == "__main__":
42 arr = [3, 4, 5, 1, 2, 3, 1]
43 result = getMinimumSum(arr)
44 print(result) # Output: 4
45
46