-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_of_number.py
More file actions
224 lines (174 loc) · 6.58 KB
/
array_of_number.py
File metadata and controls
224 lines (174 loc) · 6.58 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
'''
Given an array of numbers N and an integer k,
your task is to split N into k partitions such that the
maximum sum of any partition is minimized. Return this sum.
For example, given N = [5, 1, 2, 7, 3, 4] and k = 3,
you should return 8, since the optimal partition is [5, 1, 2],
[7], [3, 4]
'''
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(message)s")
# --------------------------------------------------
# SOLUTION 1: Binary Search + Greedy ⭐ (Optimal)
# --------------------------------------------------
def partition_array_binary_search(N, k):
"""
Minimize the maximum sum of any partition using binary search.
Approach:
- Answer is in range [max(N), sum(N)]
- Binary search on this range
- For each candidate max_sum, check if valid partition exists using greedy
Time Complexity: O(n * log(sum(N)))
Space Complexity: O(1)
"""
if k == 1:
return sum(N)
if k >= len(N):
return max(N)
def can_partition(max_sum):
"""Check if we can partition array into k parts with each sum <= max_sum"""
partitions = 1
current_sum = 0
for num in N:
if current_sum + num <= max_sum:
current_sum += num
else:
# Start a new partition
partitions += 1
current_sum = num
if partitions > k:
return False
return partitions <= k
# Binary search bounds
left = max(N) # Minimum possible maximum sum
right = sum(N) # Maximum possible maximum sum
logging.info(f"Binary search range: [{left}, {right}]")
while left < right:
mid = (left + right) // 2
logging.info(f"Testing mid={mid}")
if can_partition(mid):
# If possible, try to reduce further
right = mid
else:
# If not possible, need larger max_sum
left = mid + 1
logging.info(f"Answer found: {left}")
return left
# --------------------------------------------------
# SOLUTION 2: Dynamic Programming
# --------------------------------------------------
def partition_array_dp(N, k):
"""
Dynamic programming approach.
dp[i][j] = minimum maximum partition sum for first i elements in j partitions
Time Complexity: O(n² * k)
Space Complexity: O(n * k)
"""
n = len(N)
if k == 1:
return sum(N)
if k >= n:
return max(N)
# Prefix sum for quick range sum calculation
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + N[i]
def range_sum(i, j):
"""Sum of elements from index i to j (inclusive)"""
return prefix[j + 1] - prefix[i]
# dp[i][j] = min max sum to partition N[0:i] into j partitions
# Initialize with infinity
INF = float('inf')
dp = [[INF] * (k + 1) for _ in range(n + 1)]
# Base case: 0 elements in j partitions
dp[0][0] = 0
# Fill DP table
for i in range(1, n + 1):
for j in range(1, min(i, k) + 1):
# Try all possible positions for the last partition
for p in range(j - 1, i):
# Last partition is from p to i-1
last_partition_sum = range_sum(p, i - 1)
current_max = max(dp[p][j - 1], last_partition_sum)
dp[i][j] = min(dp[i][j], current_max)
logging.info(f"DP solution: {dp[n][k]}")
return dp[n][k]
# --------------------------------------------------
# SOLUTION 3: Greedy with Backtracking
# --------------------------------------------------
def partition_array_greedy(N, k):
"""
Greedy approach: fill partitions one by one.
Uses binary search to find the minimum possible maximum sum.
Similar to Solution 1 but with more detailed logging.
Time Complexity: O(n * log(sum(N)))
Space Complexity: O(k)
"""
if k == 1:
return sum(N)
if k >= len(N):
return max(N)
def partition_with_limit(max_sum):
"""Returns number of partitions needed if each partition <= max_sum"""
partitions = 1
current_sum = 0
partition_list = []
current_partition = []
for num in N:
if current_sum + num <= max_sum:
current_sum += num
current_partition.append(num)
else:
partition_list.append((current_partition, current_sum))
current_partition = [num]
current_sum = num
partitions += 1
partition_list.append((current_partition, current_sum))
return partitions, partition_list
left = max(N)
right = sum(N)
while left < right:
mid = (left + right) // 2
num_partitions, partitions = partition_with_limit(mid)
logging.info(f"Testing max_sum={mid}: needs {num_partitions} partitions")
if num_partitions <= k:
logging.info(f" Partitions: {partitions}")
right = mid
else:
left = mid + 1
_, final_partitions = partition_with_limit(left)
logging.info(f"Final partitions: {final_partitions}")
return left
# --------------------------------------------------
# TEST CASES
# --------------------------------------------------
def run_tests():
test_cases = [
# (N, k, expected)
([5, 1, 2, 7, 3, 4], 3, 8),
([1, 2, 3, 4, 5], 2, 7), # [1,2,4] [5] or [1,2,3] [4,5]
([1], 1, 1),
([1, 2, 3], 1, 6),
([1, 2, 3], 3, 3),
([10], 1, 10),
([4, 3, 2, 6, 5, 1], 3, 8),
([1, 1, 1, 1, 1, 1], 2, 3),
]
print("\n" + "=" * 70)
print("TESTING PARTITION ARRAY SOLUTIONS")
print("=" * 70)
for idx, (N, k, expected) in enumerate(test_cases, 1):
print(f"\n--- Test Case {idx} ---")
print(f"N = {N}, k = {k}")
print(f"Expected: {expected}")
# Test Solution 1: Binary Search
result1 = partition_array_binary_search(N.copy(), k)
print(f"Binary Search: {result1} {'✅' if result1 == expected else '❌'}")
# Test Solution 2: DP
result2 = partition_array_dp(N.copy(), k)
print(f"Dynamic Programming: {result2} {'✅' if result2 == expected else '❌'}")
# Test Solution 3: Greedy
result3 = partition_array_greedy(N.copy(), k)
print(f"Greedy with Backtracking: {result3} {'✅' if result3 == expected else '❌'}")
if __name__ == "__main__":
run_tests()