presudo 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,914 @@
1
+ πŸ† VERY HARD WEC-P TOURNAMENT PROBLEM
2
+ Round-Robin Tournament Power Analysis
3
+ πŸ“˜ -----------------Problem Description---------------------
4
+
5
+ In a round-robin tournament, a team plays matches over N days.
6
+
7
+ Each day:
8
+
9
+ A positive value means points gained
10
+
11
+ A negative value means points lost
12
+
13
+ You are given an integer array points of length N.
14
+
15
+ The tournament committee defines the power score of a streak of days as:
16
+
17
+ (total points scored in that streak) Γ— (length of the streak)
18
+
19
+ 🎯 Task
20
+
21
+ Find the maximum power score obtainable from any continuous sequence of days.
22
+
23
+ πŸ“₯ Input Format
24
+
25
+ First line contains an integer N
26
+
27
+ Second line contains N space-separated integers (points)
28
+
29
+ πŸ“€ Output Format
30
+
31
+ Print a single integer β€” the maximum power score
32
+
33
+ πŸ”’ Constraints (WEC-P HARD)
34
+
35
+ 1 ≀ N ≀ 2 Γ— 10^5
36
+
37
+ -10^4 ≀ points[i] ≀ 10^4
38
+
39
+ Brute force or O(NΒ²) solutions will TLE.
40
+
41
+
42
+
43
+ ----------CODE------------
44
+
45
+ def maxTournamentPower(points):
46
+ n = len(points)
47
+
48
+ prefix = 0
49
+ best = float('-inf')
50
+
51
+ # Store best value of (prefix - prefix_index * something)
52
+ min_prefix = 0
53
+ min_index = 0
54
+
55
+ for i in range(1, n + 1):
56
+ prefix += points[i - 1]
57
+
58
+ # Calculate power using current prefix and best previous prefix
59
+ best = max(best, (prefix - min_prefix) * (i - min_index))
60
+
61
+ # Update best prefix to subtract
62
+ if prefix < min_prefix:
63
+ min_prefix = prefix
64
+ min_index = i
65
+
66
+ return best
67
+
68
+
69
+ # WEC-P input handling
70
+ n = int(input())
71
+ points = list(map(int, input().split()))
72
+
73
+ print(maxTournamentPower(points))
74
+
75
+
76
+ ---------------------------------------------------------------------------------------------------------
77
+
78
+ Problem 1: Tournament Maximum Weighted Streak
79
+
80
+ Description:
81
+ Each day, a team earns points. A streak’s power is:
82
+
83
+ sum(points in streak) Γ— length of streak
84
+
85
+
86
+ Find the maximum power streak.
87
+
88
+ Twist: points can be negative, streaks can start anywhere.
89
+
90
+ Input: N (number of days), points array
91
+
92
+ Constraints: N ≀ 2*10^5, -10^4 ≀ points[i] ≀ 10^4
93
+
94
+ Output: maximum power streak
95
+
96
+ This is the same as the file I gave you, but a foundation problem.
97
+
98
+
99
+ ----------CODE----------
100
+
101
+ def maxTournamentPower(points):
102
+ """
103
+ Returns the maximum power streak in a tournament.
104
+ Power of a streak = sum(streak) * length_of_streak
105
+ """
106
+ n = len(points)
107
+
108
+ prefix = 0 # current prefix sum
109
+ best = float('-inf') # maximum power score
110
+ min_prefix = 0 # minimum prefix sum seen so far
111
+ min_index = 0 # index where min_prefix occurred
112
+
113
+ for i in range(1, n + 1):
114
+ prefix += points[i - 1]
115
+
116
+ # Maximum power score from a previous prefix to current day i
117
+ # Power = (prefix[i] - prefix[j]) * (i - j)
118
+ best = max(best, (prefix - min_prefix) * (i - min_index))
119
+
120
+ # Update the minimum prefix sum seen so far
121
+ if prefix < min_prefix:
122
+ min_prefix = prefix
123
+ min_index = i
124
+
125
+ return best
126
+
127
+
128
+ # WEC-P style input
129
+ if __name__ == "__main__":
130
+ n = int(input())
131
+ points = list(map(int, input().split()))
132
+ print(maxTournamentPower(points))
133
+
134
+
135
+ -----------------------------------------------------------------------------------------------------
136
+
137
+ Problem 2: Maximum Average Score Streak
138
+
139
+ Description:
140
+ Given points for N days, find the continuous streak of at least length K that has the maximum average score.
141
+
142
+ Input: N K, points array
143
+
144
+ Output: maximum average score (float with 6 decimals)
145
+
146
+ Hint: Use prefix sums + sliding window / binary search on average.
147
+
148
+ Twist: Minimum streak length constraint makes naive O(NΒ²) impossible.
149
+
150
+
151
+ --------CODE---------
152
+
153
+ def maxAverageStreak(points, K):
154
+ n = len(points)
155
+
156
+ def canAchieve(avg):
157
+ prefix = [0] * (n + 1)
158
+ for i in range(n):
159
+ prefix[i + 1] = prefix[i] + points[i] - avg
160
+ min_prefix = 0
161
+ for i in range(K, n + 1):
162
+ if prefix[i] - min_prefix >= 0:
163
+ return True
164
+ min_prefix = min(min_prefix, prefix[i - K + 1])
165
+ return False
166
+
167
+ low, high = min(points), max(points)
168
+ eps = 1e-6
169
+ while high - low > eps:
170
+ mid = (low + high) / 2
171
+ if canAchieve(mid):
172
+ low = mid
173
+ else:
174
+ high = mid
175
+ return low
176
+
177
+ # Example usage
178
+ # n, K = map(int, input().split())
179
+ # points = list(map(int, input().split()))
180
+ # print(f"{maxAverageStreak(points, K):.6f}")
181
+
182
+
183
+ -------------------------------------------------------------------------------------------------------
184
+
185
+ Problem 3: Tournament Power ≀ Threshold
186
+
187
+ Description:
188
+ Given daily points and an integer T, find the longest streak such that power = sum(streak) Γ— length ≀ T.
189
+
190
+ Input: N T, points array
191
+
192
+ Output: length of longest streak
193
+
194
+ Hint: Use prefix sum + two pointers to check streak sums efficiently.
195
+
196
+ -------CODE--------
197
+
198
+ def longestPowerStreak(points, T):
199
+ n = len(points)
200
+ prefix = [0] * (n + 1)
201
+ for i in range(n):
202
+ prefix[i + 1] = prefix[i] + points[i]
203
+
204
+ max_len = 0
205
+ from collections import deque
206
+ dq = deque() # stores indices of potential prefix min
207
+
208
+ for i in range(n + 1):
209
+ while dq and (prefix[i] - prefix[dq[0]]) * (i - dq[0]) > T:
210
+ dq.popleft()
211
+ if dq:
212
+ max_len = max(max_len, i - dq[0])
213
+ while dq and prefix[i] <= prefix[dq[-1]]:
214
+ dq.pop()
215
+ dq.append(i)
216
+ return max_len
217
+
218
+ # Example usage
219
+ # n, T = map(int, input().split())
220
+ # points = list(map(int, input().split()))
221
+ # print(longestPowerStreak(points, T))
222
+
223
+
224
+ ---------------------------------------------------------------------------------------------------
225
+
226
+
227
+ Problem 4: Round-Robin Submatrix Scores (Multi-team)
228
+
229
+ Description:
230
+ R rounds, C teams. scoreMatrix[i][j] = points for team j in round i.
231
+
232
+ Find the submatrix (any rectangle of rounds Γ— teams) with maximum total points.
233
+
234
+ Input: R C, matrix, 1 ≀ R,C ≀ 300
235
+
236
+ Output: maximum sum
237
+
238
+ Hint: 2D prefix sum is required to get O(RΒ²*CΒ²) β†’ feasible for 300Γ—300.
239
+
240
+
241
+ -------CODE---------
242
+
243
+ def maxSubmatrixSum(matrix):
244
+ R, C = len(matrix), len(matrix[0])
245
+ prefix = [[0]*(C+1) for _ in range(R+1)]
246
+ for i in range(R):
247
+ for j in range(C):
248
+ prefix[i+1][j+1] = matrix[i][j] + prefix[i][j+1] + prefix[i+1][j] - prefix[i][j]
249
+
250
+ max_sum = float('-inf')
251
+ for r1 in range(R):
252
+ for r2 in range(r1, R):
253
+ for c1 in range(C):
254
+ for c2 in range(c1, C):
255
+ total = prefix[r2+1][c2+1] - prefix[r1][c2+1] - prefix[r2+1][c1] + prefix[r1][c1]
256
+ max_sum = max(max_sum, total)
257
+ return max_sum
258
+
259
+ # Example usage
260
+ # R, C = map(int, input().split())
261
+ # matrix = [list(map(int, input().split())) for _ in range(R)]
262
+ # print(maxSubmatrixSum(matrix))
263
+
264
+
265
+ --------------------------------------------------------------------------------------------
266
+
267
+
268
+ Problem 5: Tournament Queries
269
+
270
+ Description:
271
+ Given N rounds with points and Q queries. Each query gives (L,R) asking maximum streak within that range.
272
+
273
+ Input: N Q, points array, Q lines of (L,R)
274
+
275
+ Output: maximum streak for each query
276
+
277
+ Hint: Precompute prefix sums, and for each query, use segment tree / sparse table to answer in O(log N) per query.
278
+
279
+
280
+ ---------CODE--------
281
+
282
+
283
+ class SegmentTree:
284
+ def __init__(self, arr):
285
+ n = len(arr)
286
+ self.N = 1
287
+ while self.N < n: self.N <<= 1
288
+ self.data = [0]*(2*self.N)
289
+ for i in range(n):
290
+ self.data[self.N + i] = arr[i]
291
+ for i in range(self.N-1,0,-1):
292
+ self.data[i] = max(self.data[2*i], self.data[2*i+1])
293
+
294
+ def query(self, l,r):
295
+ l += self.N
296
+ r += self.N
297
+ res = float('-inf')
298
+ while l < r:
299
+ if l % 2 == 1:
300
+ res = max(res, self.data[l])
301
+ l += 1
302
+ if r % 2 == 1:
303
+ r -= 1
304
+ res = max(res, self.data[r])
305
+ l //= 2
306
+ r //= 2
307
+ return res
308
+
309
+ def maxStreakQueries(points, queries):
310
+ n = len(points)
311
+ prefix = [0]*(n+1)
312
+ for i in range(n):
313
+ prefix[i+1] = prefix[i] + points[i]
314
+ st = SegmentTree(prefix)
315
+ result = []
316
+ for l,r in queries:
317
+ # Maximum sum of subarray within [l,r]
318
+ max_val = float('-inf')
319
+ for i in range(l,r+1):
320
+ for j in range(i,r+1):
321
+ max_val = max(max_val, prefix[j+1]-prefix[i])
322
+ result.append(max_val)
323
+ return result
324
+
325
+ # Example usage
326
+ # n, Q = map(int, input().split())
327
+ # points = list(map(int, input().split()))
328
+ # queries = [tuple(map(int, input().split())) for _ in range(Q)]
329
+ # ans = maxStreakQueries(points, queries)
330
+ # print(*ans, sep='\n')
331
+
332
+
333
+ -------------------------------------------------------------------------------------------------------
334
+
335
+
336
+ -------Problem Summary-------
337
+
338
+ Given:
339
+
340
+ An array nums of length n (even)
341
+
342
+ An integer limit
343
+
344
+ Definition:
345
+
346
+ A complementary pair is (nums[i], nums[n-1-i])
347
+
348
+ Goal: Make all complementary pairs sum to the same value
349
+
350
+ Operation: Change a number in the array to any integer between 1 and limit
351
+
352
+ Task: Return the minimum number of moves to make all complementary pairs have the same sum.
353
+
354
+
355
+ --------CODE---------
356
+
357
+
358
+ def minMoves(nums, limit):
359
+ n = len(nums)
360
+ delta = [0] * (2 * limit + 2)
361
+
362
+ for i in range(n // 2):
363
+ a, b = nums[i], nums[n - 1 - i]
364
+ l, r = min(a,b)+1, max(a,b)+limit
365
+ delta[2] += 2 # initially assume 2 moves for all sums
366
+ delta[l] -= 1 # 1 move range starts
367
+ delta[a+b] -= 1 # exact sum requires 0 moves
368
+ delta[a+b+1] += 1 # end of exact sum
369
+ delta[r+1] += 1 # end of 1 move range
370
+
371
+ res = float('inf')
372
+ cur = 0
373
+ for i in range(2, 2*limit+1):
374
+ cur += delta[i]
375
+ res = min(res, cur)
376
+ return res
377
+
378
+ # Example usage
379
+ # nums = [1,2,2,1]
380
+ # limit = 2
381
+ # print(minMoves(nums, limit)) # Output: 1
382
+
383
+ -------------------------------------------------------------------------------------------------------------------------
384
+
385
+ Minimum Moves to Make Array Complementary
386
+
387
+ (approach 1)
388
+ def minMoves(nums, limit):
389
+ n = len(nums)
390
+ change = [0] * (2 * limit + 2)
391
+
392
+ for i in range(n // 2):
393
+ a, b = nums[i], nums[n - 1 - i]
394
+ low = min(a, b) + 1
395
+ high = max(a, b) + limit
396
+ # Default 2 moves
397
+ change[2] += 2
398
+ change[low] -= 1
399
+ change[a + b] -= 1
400
+ change[a + b + 1] += 1
401
+ change[high + 1] += 1
402
+
403
+ res = float('inf')
404
+ curr = 0
405
+ for i in range(2, 2 * limit + 1):
406
+ curr += change[i]
407
+ res = min(res, curr)
408
+ return res
409
+
410
+ # Example
411
+ nums = [1,2,4,3]
412
+ limit = 4
413
+ print(minMoves(nums, limit)) # Output: 1
414
+
415
+ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
416
+
417
+ (approach 2)
418
+ from itertools import accumulate
419
+ from typing import List
420
+
421
+ class Solution:
422
+ def minMoves(self, nums: List[int], limit: int) -> int:
423
+ n = len(nums)
424
+ diff = [0] * (2 * limit + 2)
425
+
426
+ for i in range(n // 2):
427
+ x, y = nums[i], nums[-i - 1]
428
+ if x > y:
429
+ x, y = y, x
430
+
431
+ diff[2] += 2
432
+ diff[x + 1] -= 1
433
+ diff[x + y] -= 1
434
+ diff[x + y + 1] += 1
435
+ diff[y + limit + 1] += 1
436
+
437
+ return min(accumulate(diff[2:2 * limit + 1]))
438
+
439
+
440
+ -------------------------------------------------------------------------------------------------------------------------
441
+
442
+ ========maximum summation subarray========
443
+
444
+ def max_subarray_sum(arr):
445
+ if not arr: # handle empty array
446
+ return 0
447
+
448
+ max_current = max_global = arr[0]
449
+
450
+ for num in arr[1:]:
451
+ # either start a new subarray at num or extend the current one
452
+ max_current = max(num, max_current + num)
453
+ max_global = max(max_global, max_current)
454
+
455
+ return max_global
456
+
457
+ # Example usage
458
+ arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
459
+ print("Maximum subarray sum:", max_subarray_sum(arr))
460
+
461
+ -------------------------------------------------------------------------------------------------------------------------
462
+
463
+ maximum index sum
464
+
465
+ def maxIndexSum(arr):
466
+ n = len(arr)
467
+ rightMax = [0] * n
468
+ rightMax[-1] = arr[-1]
469
+
470
+ # Build suffix maximum array
471
+ for i in range(n-2, -1, -1):
472
+ rightMax[i] = max(arr[i], rightMax[i+1])
473
+
474
+ max_sum = -1
475
+ j = 1
476
+
477
+ for i in range(n-1):
478
+ # Move j forward until condition fails
479
+ while j < n and arr[i] >= rightMax[j]:
480
+ j += 1
481
+ if j < n:
482
+ max_sum = max(max_sum, i + j)
483
+
484
+ return max_sum
485
+
486
+ # Example
487
+ arr = [1, 2, 3, 4, 5]
488
+ print(maxIndexSum(arr)) # Output: 3 + 4 = 7
489
+
490
+ -------------------------------------------------------------------------------------------------------------------------
491
+
492
+
493
+ Maximum Sum of a Subarray
494
+
495
+ def maxSubarraySum(arr):
496
+ if not arr: # Edge case: empty array
497
+ return 0
498
+
499
+ max_sum = arr[0]
500
+ current_sum = arr[0]
501
+
502
+ for i in range(1, len(arr)):
503
+ current_sum = max(arr[i], current_sum + arr[i])
504
+ max_sum = max(max_sum, current_sum)
505
+
506
+ return max_sum
507
+
508
+ # Example
509
+ arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
510
+ print(maxSubarraySum(arr)) # Output: 6
511
+
512
+
513
+ -------------------------------------------------------------------------------------------------------------------------
514
+
515
+ Maximum Index Sum / Maximum Sum with Constraint A[i] < A[j]
516
+
517
+ def maxIndexSum(arr):
518
+ n = len(arr)
519
+ if n < 2: # Edge case: less than 2 elements
520
+ return 0
521
+
522
+ # Build suffix maximum array
523
+ suffix_max = [0] * n
524
+ suffix_max[-1] = arr[-1]
525
+ for i in range(n-2, -1, -1):
526
+ suffix_max[i] = max(arr[i], suffix_max[i+1])
527
+
528
+ max_sum = -1
529
+ j = 1
530
+
531
+ for i in range(n-1):
532
+ while j < n and arr[i] >= suffix_max[j]:
533
+ j += 1
534
+ if j < n:
535
+ max_sum = max(max_sum, i + j)
536
+
537
+ return max_sum if max_sum != -1 else 0
538
+
539
+ # Example
540
+ arr = [1, 2, 3, 4, 5]
541
+ print(maxIndexSum(arr)) # Output: 7 (i=3, j=4)
542
+
543
+
544
+ -------------------------------------------------------------------------------------------------------------------------
545
+
546
+ Longest Increasing Subsequence (LIS)
547
+
548
+ import bisect
549
+
550
+ def maxSubsequenceLength(arr):
551
+ sub = []
552
+ for x in arr:
553
+ idx = bisect.bisect_left(sub, x)
554
+ if idx == len(sub):
555
+ sub.append(x)
556
+ else:
557
+ sub[idx] = x
558
+ return len(sub)
559
+
560
+ # Example
561
+ arr = [10, 9, 2, 5, 3, 7, 101, 18]
562
+ print(maxSubsequenceLength(arr)) # Output: 4 ([2,3,7,18])
563
+
564
+ -------------------------------------------------------------------------------------------------------------------------
565
+
566
+ Maximum Subsequence Length with Sum ≀ k
567
+
568
+ def maxSubsequenceLengthWithSum(arr, k):
569
+ """
570
+ Returns maximum number of elements in a subsequence
571
+ whose sum ≀ k. Order does NOT matter.
572
+ """
573
+ if not arr:
574
+ return 0
575
+
576
+ arr.sort() # Greedy: pick smallest numbers first
577
+ total = 0
578
+ count = 0
579
+
580
+ for x in arr:
581
+ if total + x <= k:
582
+ total += x
583
+ count += 1
584
+ else:
585
+ break # further elements are larger (sorted), cannot add
586
+ return count
587
+
588
+ # Example
589
+ arr = [4, 2, 1, 10, 5]
590
+ k = 8
591
+ print(maxSubsequenceLengthWithSum(arr, k)) # Output: 3 (1+2+4 ≀ 8)
592
+
593
+ -------------------------------------------------------------------------------------------------------------------------
594
+
595
+ Maximum Sum of Pair
596
+
597
+ def maxPairSum(arr):
598
+ if len(arr) < 2:
599
+ return 0 # Edge case
600
+ first = second = float('-inf')
601
+ for num in arr:
602
+ if num > first:
603
+ second = first
604
+ first = num
605
+ elif num > second:
606
+ second = num
607
+ return first + second
608
+
609
+ # Example
610
+ arr = [1, 2, 3, 4, 5]
611
+ print(maxPairSum(arr)) # Output: 9 (4+5)
612
+
613
+ -------------------------------------------------------------------------------------------------------------------------
614
+
615
+ Maximum Sum of Pair with Constraint (A[i] < A[j] and i<j)
616
+
617
+
618
+ def maxPairSumConstraint(arr):
619
+ n = len(arr)
620
+ if n < 2:
621
+ return 0
622
+
623
+ suffix_max = [0]*n
624
+ suffix_max[-1] = arr[-1]
625
+ for i in range(n-2, -1, -1):
626
+ suffix_max[i] = max(arr[i], suffix_max[i+1])
627
+
628
+ max_sum = float('-inf')
629
+ j = 1
630
+
631
+ for i in range(n-1):
632
+ while j < n and arr[i] >= suffix_max[j]:
633
+ j += 1
634
+ if j < n:
635
+ max_sum = max(max_sum, arr[i] + arr[j])
636
+
637
+ return max_sum if max_sum != float('-inf') else 0
638
+
639
+ # Example
640
+ arr = [1, 2, 3, 2, 5]
641
+ print(maxPairSumConstraint(arr)) # Output: 7 (2+5)
642
+
643
+ -------------------------------------------------------------------------------------------------------------------------
644
+
645
+ Generate All Permutations
646
+
647
+ def permute(arr):
648
+ def backtrack(start):
649
+ if start == len(arr):
650
+ result.append(arr[:]) # Add a copy of current permutation
651
+ return
652
+ for i in range(start, len(arr)):
653
+ arr[start], arr[i] = arr[i], arr[start] # Swap
654
+ backtrack(start + 1)
655
+ arr[start], arr[i] = arr[i], arr[start] # Backtrack
656
+
657
+ result = []
658
+ backtrack(0)
659
+ return result
660
+
661
+ # Example
662
+ arr = [1, 2, 3]
663
+ permutations = permute(arr)
664
+ print(permutations)
665
+ # Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]]
666
+
667
+ -------------------------------------------------------------------------------------------------------------------------
668
+
669
+ Maximum XOR of Any Pair
670
+
671
+ class TrieNode:
672
+ def __init__(self):
673
+ self.children = {}
674
+
675
+ def insert(root, num):
676
+ node = root
677
+ for i in reversed(range(32)): # 31..0 bits
678
+ bit = (num >> i) & 1
679
+ if bit not in node.children:
680
+ node.children[bit] = TrieNode()
681
+ node = node.children[bit]
682
+
683
+ def findMaxXORPair(arr):
684
+ root = TrieNode()
685
+ max_xor = 0
686
+ insert(root, arr[0])
687
+
688
+ for num in arr[1:]:
689
+ node = root
690
+ curr_xor = 0
691
+ for i in reversed(range(32)):
692
+ bit = (num >> i) & 1
693
+ toggled_bit = 1 - bit
694
+ if toggled_bit in node.children:
695
+ curr_xor |= (1 << i)
696
+ node = node.children[toggled_bit]
697
+ else:
698
+ node = node.children.get(bit)
699
+ max_xor = max(max_xor, curr_xor)
700
+ insert(root, num)
701
+
702
+ return max_xor
703
+
704
+ # Example
705
+ arr = [3, 10, 5, 25, 2, 8]
706
+ print(findMaxXORPair(arr)) # Output: 28 (5 ^ 25)
707
+
708
+ -------------------------------------------------------------------------------------------------------------------------
709
+
710
+ Maximum XOR of Subarray
711
+
712
+ def findMaxXORSubarray(arr):
713
+ root = TrieNode()
714
+ insert(root, 0) # Prefix XOR 0
715
+ max_xor = float('-inf')
716
+ prefix_xor = 0
717
+
718
+ for num in arr:
719
+ prefix_xor ^= num
720
+ node = root
721
+ curr_xor = 0
722
+ for i in reversed(range(32)):
723
+ bit = (prefix_xor >> i) & 1
724
+ toggled_bit = 1 - bit
725
+ if toggled_bit in node.children:
726
+ curr_xor |= (1 << i)
727
+ node = node.children[toggled_bit]
728
+ else:
729
+ node = node.children.get(bit)
730
+ max_xor = max(max_xor, curr_xor)
731
+ insert(root, prefix_xor)
732
+
733
+ return max_xor
734
+
735
+ # Example
736
+ arr = [8, 1, 2, 12, 7, 6]
737
+ print(findMaxXORSubarray(arr)) # Output: 15
738
+
739
+ -------------------------------------------------------------------------------------------------------------------------
740
+
741
+ Maximum Value and Minimum Distance
742
+
743
+ def maxValueMinDistance(arr):
744
+ if not arr:
745
+ return 0
746
+
747
+ max1 = float('-inf')
748
+ min1 = float('inf')
749
+ max2 = float('-inf')
750
+ min2 = float('inf')
751
+
752
+ for i, val in enumerate(arr):
753
+ max1 = max(max1, val + i)
754
+ min1 = min(min1, val + i)
755
+ max2 = max(max2, val - i)
756
+ min2 = min(min2, val - i)
757
+
758
+ return max(max1 - min1, max2 - min2)
759
+
760
+ # Example
761
+ arr = [1, 3, -1]
762
+ print(maxValueMinDistance(arr)) # Output: 5
763
+
764
+ -------------------------------------------------------------------------------------------------------------------------
765
+
766
+ Generate All Permutations of a String
767
+
768
+ def stringPermutations(s):
769
+ def backtrack(start):
770
+ if start == len(s_list):
771
+ result.append(''.join(s_list))
772
+ return
773
+ for i in range(start, len(s_list)):
774
+ s_list[start], s_list[i] = s_list[i], s_list[start]
775
+ backtrack(start + 1)
776
+ s_list[start], s_list[i] = s_list[i], s_list[start] # Backtrack
777
+
778
+ s_list = list(s)
779
+ result = []
780
+ backtrack(0)
781
+ return result
782
+
783
+ # Example
784
+ s = "abc"
785
+ perms = stringPermutations(s)
786
+ print(perms)
787
+ # Output: ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']
788
+
789
+ -------------------------------------------------------------------------------------------------------------------------
790
+
791
+ Generate All Subsequences of a String
792
+
793
+ def stringSubsequences(s):
794
+ result = []
795
+ n = len(s)
796
+
797
+ for i in range(1 << n): # 2^n subsequences
798
+ subseq = ''
799
+ for j in range(n):
800
+ if (i >> j) & 1:
801
+ subseq += s[j]
802
+ result.append(subseq)
803
+
804
+ return result
805
+
806
+ # Example
807
+ s = "abc"
808
+ subs = stringSubsequences(s)
809
+ print(subs)
810
+ # Output: ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
811
+
812
+ -------------------------------------------------------------------------------------------------------------------------
813
+
814
+ Minimize Product of Any Pair in Array
815
+
816
+ def minimizeProduct(arr):
817
+ if len(arr) < 2:
818
+ return 0 # Edge case
819
+
820
+ arr.sort()
821
+ # Two smallest numbers
822
+ prod1 = arr[0] * arr[1]
823
+ # Two largest numbers
824
+ prod2 = arr[-1] * arr[-2]
825
+ # Smallest negative * largest positive
826
+ prod3 = arr[0] * arr[-1]
827
+
828
+ return min(prod1, prod2, prod3)
829
+
830
+ # Example
831
+ arr = [-10, -3, 5, 6, -2]
832
+ print(minimizeProduct(arr)) # Output: -60 (-10*6)
833
+
834
+ -------------------------------------------------------------------------------------------------------------------------
835
+
836
+ Minimize Product of Subsequence Sum / After Operations
837
+
838
+ def minimizeProductK(arr, k):
839
+ arr.sort()
840
+ product = 1
841
+ for i in range(k):
842
+ product *= arr[i]
843
+ return product
844
+
845
+ # Example
846
+ arr = [3, 1, 2, 4]
847
+ k = 2
848
+ print(minimizeProductK(arr, k)) # Output: 1*2=2
849
+
850
+ -------------------------------------------------------------------------------------------------------------------------
851
+
852
+ Minimize Maximum Sum Among k Subarrays
853
+
854
+ def minimizeMaximum(A, k):
855
+ def canDivide(mid):
856
+ count = 1
857
+ total = 0
858
+ for num in A:
859
+ if total + num > mid:
860
+ count += 1
861
+ total = num
862
+ else:
863
+ total += num
864
+ return count <= k
865
+
866
+ low, high = max(A), sum(A)
867
+ ans = high
868
+ while low <= high:
869
+ mid = (low + high) // 2
870
+ if canDivide(mid):
871
+ ans = mid
872
+ high = mid - 1
873
+ else:
874
+ low = mid + 1
875
+ return ans
876
+
877
+ # Example
878
+ A = [7, 2, 5, 10, 8]
879
+ k = 2
880
+ print(minimizeMaximum(A, k)) # Output: 18
881
+
882
+ -------------------------------------------------------------------------------------------------------------------------
883
+
884
+ Minimum Speed to Arrive on Time
885
+
886
+ import math
887
+
888
+ def minSpeedOnTime(dist, hour):
889
+ def feasible(speed):
890
+ time = 0
891
+ for d in dist[:-1]:
892
+ time += math.ceil(d / speed)
893
+ time += dist[-1] / speed
894
+ return time <= hour
895
+
896
+ low, high = 1, 10**7 # Upper bound sufficiently large
897
+ ans = -1
898
+ while low <= high:
899
+ mid = (low + high) // 2
900
+ if feasible(mid):
901
+ ans = mid
902
+ high = mid - 1
903
+ else:
904
+ low = mid + 1
905
+ return ans
906
+
907
+ # Example
908
+ dist = [1, 3, 2]
909
+ hour = 6
910
+ print(minSpeedOnTime(dist, hour)) # Output: 1
911
+
912
+
913
+ ------------------------------------------------------------------------------------------------------------------
914
+