Repository navigation
Expand file tree
/
Copy pathLeetCode5.cpp
More file actions
1331 lines (1060 loc) · 31.6 KB
/
Copy pathLeetCode5.cpp
File metadata and controls
1331 lines (1060 loc) · 31.6 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <algorithm>
#include <typeinfo>
#include <cctype>
#include <climits>
#include <utility>
#include <cmath>
#include <numeric>
#include <iterator>
#include <functional>
#include <vector>
#include <array>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <tuple>
using namespace std;
// Data Structures
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
// Oct 2026
// 20. Valid Parentheses, Stack
bool isValid(string s) {
stack<char> st;
for (const char& ch: s) {
if (ch == ')') {
if (st.empty()) {
return false;
} else if (st.top() != '(') {
return false;
}
st.pop();
} else if (ch == '}') {
if (st.empty()) {
return false;
} else if (st.top() != '{') {
return false;
}
st.pop();
} else if (ch == ']') {
if (st.empty()) {
return false;
} else if (st.top() != '[') {
return false;
}
st.pop();
} else {
st.push(ch);
}
}
return st.empty();
}
// 22. Generate Parentheses, BackTrack
void generateParenthesisRec(int open, int close, int n, int idx, string& s, vector<string>& ans) {
// Base Case
if (idx == (2 * n)) {
ans.push_back(s);
return;
}
// Times bracket can open
if (open < n) {
s[idx] = '(';
generateParenthesisRec(open + 1, close, n, idx + 1, s, ans);
}
// Times bracket can close
if (close < open) {
s[idx] = ')';
generateParenthesisRec(open, close + 1, n, idx + 1, s, ans);
}
return;
}
vector<string> generateParenthesis(int n) {
// Removes all push and pop and resizing of string
string s(2 * n, '(');
vector<string> ans;
// Function call
generateParenthesisRec(0, 0, n, 0, s, ans);
return ans;
}
// 32. Longest Valid Parentheses, Stack
int longestValidParentheses(string s) {
const int size = s.size();
int ans = 0;
stack<int> st;
st.push(-1);
for (int i = 0; i < size; i++) {
// Current longest valid parentheses
if (s[i] == ')' && st.top() != -1 && s[st.top()] == '(') {
st.pop();
ans = max(ans, i - st.top());
} else {
// Last known stop
st.push(i);
}
}
return ans;
}
// 678. Valid Parenthesis String, Stack and Deque
bool checkValidString(string s) {
const int size = s.size();
bool closeFound = false;
stack<int> open;
deque<int> star;
for (int i = 0; i < size; i++) {
const char ch = s[i];
if (ch == '(') {
// Pushing in stack
open.push(i);
} else if (ch == ')') {
if (!open.empty()) {
// Popping the latest open bracket
open.pop();
} else {
// Needed a star
closeFound = true;
}
} else {
// Star
star.push_back(i);
}
if (closeFound) {
if (star.size() > 0) {
// Star acts as '('
// Remove the first star, as maybe the later on stars are needed by a '('
star.pop_front();
closeFound = false;
} else {
// Can't close
return false;
}
}
}
// "**(" checker
while (!open.empty() && !star.empty()) {
// No star for open bracket
if (open.top() > star.back()) {
return false;
}
// Star acts as ')'
open.pop();
star.pop_back();
}
// All brackets are closed
return open.empty();
}
// 856. Score of Parentheses, Stack
int scoreOfParentheses(string s) {
stack<int> st;
// For whole string
st.push(0);
for (const char& ch: s) {
if (ch == '(') {
st.push(0);
} else {
const int firstLayer = st.top();
st.pop();
const int secondLayer = st.top();
st.pop();
// Own closing bracket
if (firstLayer == 0) {
st.push(secondLayer + firstLayer + 1);
} else {
// Second layer i.e neighbour or covering
st.push(secondLayer + (2 * firstLayer));
}
}
}
return st.top();
}
// 921. Minimum Add to Make Parentheses Valid, Counting
int minAddToMakeValid(string s) {
int invalidOpen = 0;
int invalidClose = 0;
for (const char& ch: s) {
if (ch == '(') {
invalidOpen++;
} else {
if (invalidOpen == 0) {
// Incorrect closing bracket
invalidClose++;
} else {
// Correct closing bracket
invalidOpen--;
}
}
}
return invalidOpen + invalidClose;
}
// 301. Remove Invalid Parentheses, Recursion + BackTrack
// Valid parentheses checker
bool removeInvalidParenthesesCheck(string& s) {
int invalidOpen = 0;
int invalidClose = 0;
for (const char& ch: s) {
if (ch == '(') {
invalidOpen++;
} else if (ch == ')') {
if (invalidOpen == 0) {
invalidClose++;
} else {
invalidOpen--;
}
}
}
return (invalidOpen + invalidClose == 0);
}
// Constructing strings
void removeInvalidParenthesesRec(int idx, int open, int close, string& s, string& str, set<string>& st) {
// Base Case
if (idx >= str.size()) {
// Checking for all conditions
if ( open == 0 && close == 0 && removeInvalidParenthesesCheck(s) ) {
st.insert(s);
}
return;
}
const char ch = str[idx];
// Exclude cases
if (ch == '(' && open > 0) {
removeInvalidParenthesesRec(idx + 1, open - 1, close, s, str, st);
} else if (ch == ')' && close > 0) {
removeInvalidParenthesesRec(idx + 1, open, close - 1, s, str, st);
}
// Include
s.push_back(ch);
removeInvalidParenthesesRec(idx + 1, open, close, s, str, st);
s.pop_back();
return;
}
vector<string> removeInvalidParentheses(string str) {
int invalidOpen = 0;
int invalidClose = 0;
// Counting all the invalid '(' & ')'
for (const char& ch: str) {
if (ch == '(') {
invalidOpen++;
} else if (ch == ')') {
if (invalidOpen == 0) {
invalidClose++;
} else {
invalidOpen--;
}
}
}
string s = "";
set<string> st;
removeInvalidParenthesesRec(0, invalidOpen, invalidClose, s, str, st);
return vector<string>(st.begin(), st.end());
}
// 1021. Remove Outermost Parentheses, Two-Pointers
string removeOuterParentheses(string s) {
const int size = s.size();
int l = 0;
int cnt = 0;
string ans = "";
ans.reserve(size - 2);
for (int r = 0; r < size; r++) {
if (s[r] == '(') {
cnt++;
} else {
cnt--;
}
// Valid parentheses
if (cnt == 0) {
ans += s.substr(l + 1, r - l - 1);
l = r + 1;
}
}
return ans;
}
// 1541. Minimum Insertions to Balance a Parentheses String, Counting
int minInsertions(string s) {
const int size = s.size();
int ans = 0;
int cnt = 0;
for (int i = 0; i < size; i++) {
if (s[i] == '(') {
cnt++;
} else {
// We have previous opening brackets
if (cnt > 0) {
if (i < size - 1 && s[i + 1] == ')') {
// Simple closing case
i++;
} else {
// 2 cases: i == size - 1, s[i + 1] == '('
ans++;
}
cnt--;
} else {
if (i < size - 1 && s[i + 1] == ')') {
// Adding a '('
i++;
ans++;
} else {
// 2 cases: i == size - 1, s[i + 1] == '('
// Adding '(' && ')' on both side of s[i]
ans += 2;
}
}
}
}
// If we have extra closing brackets
if (cnt > 0) {
ans += (cnt * 2);
}
return ans;
}
// Weekly 522
// 4070. Minimum Rotations to Dial a Number I, Mod
int minRotations(string s) {
int ans = 0;
int prev = 0;
for (const char& ch: s) {
const int curr = ch - '0';
// Left and right distance
ans += min((curr - prev + 10) % 10, (prev - curr + 10) % 10);
prev = curr;
}
return ans;
}
// 4071. Minimum Rotations to Dial a Number II, Mod
int minRotations(int n, string s) {
int ans = 0;
int prev = 0;
int maxRev = 0;
const int last = s[n - 1] - '0';
for (const char& ch: s) {
const int curr = ch - '0';
// Left and right distance
int dist = min((curr - prev + 10) % 10, (prev - curr + 10) % 10);
ans += dist;
// If curr is swapped with last
int swapDist = min((last - prev + 10) % 10, (prev - last + 10) % 10);
maxRev = max(maxRev, dist - swapDist);
prev = curr;
}
// Most useful swap
return ans - maxRev;
}
// 4072. Maximum Alternating Subarray Sum With One Deletion, Subarray 3D-DP
// Memoization
long long maxAlternatingSumMemo(int i, int parity, int isDel, vector<int>& nums, vector<vector<vector<long long>>>& dp) {
// Base Case
if (i >= nums.size()) {
return 0;
}
if (dp[i][parity][isDel] != LLONG_MIN) {
return dp[i][parity][isDel];
}
// It can stop here with the help of 0, if future goes negative, so no LLONG_MIN
long long ans = 0;
long long val = 0;
if (parity == 0) {
val = 1LL * nums[i];
} else {
val = -1LL * nums[i];
}
// Include in subarray
long long include = val + maxAlternatingSumMemo(i + 1, 1 - parity, isDel, nums, dp);
ans = max(ans, include);
// Exclude in subarray
if (isDel == 0) {
long long exclude = maxAlternatingSumMemo(i + 1, parity, 1, nums, dp);
ans = max(ans, exclude);
}
return dp[i][parity][isDel] = ans;
}
// Tabulation
long long maxAlternatingSumTab(vector<int>& nums) {
const int size = nums.size();
vector<vector<vector<long long>>> dp(size + 1, vector<vector<long long>>(2, vector<long long>(2, 0)));
// Bottom-Up
for (int i = size - 1; i >= 0; i--) {
for (int parity = 0; parity < 2; parity++) {
for (int isDel = 0; isDel < 2; isDel++) {
long long val = 0;
// It can stop here with the help of 0, if future goes negative
long long ans = 0;
if (parity == 0) {
val = 1LL * nums[i];
} else {
val = -1LL * nums[i];
}
// Include in subarray
long long include = val + dp[i + 1][1 - parity][isDel];
ans = max(ans, include);
// Exclude in subarray
if (isDel == 0) {
long long exclude = dp[i + 1][parity][1];
ans = max(ans, exclude);
}
dp[i][parity][isDel] = ans;
}
}
}
long long finalAns = LLONG_MIN;
// Taking the best
for (int i = 0; i < size; i++) {
// Since we do a 0 at nums.size(), single element can be skipped and also
long long curr = nums[i] + dp[i + 1][1][0];
finalAns = max(finalAns, curr);
}
return finalAns;
}
// Tabulation SO
long long maxAlternatingSumTabSO(vector<int>& nums) {
const int size = nums.size();
long long finalAns = LLONG_MIN;
vector<vector<long long>> curr(2, vector<long long>(2, 0));
vector<vector<long long>> next(2, vector<long long>(2, 0));
// Bottom-Up
for (int i = size - 1; i >= 0; i--) {
// Since we do a 0 at nums.size(), single element can be skipped and also
// Curr cause dp[i + 1] i.e next got swapped with curr
long long currAns = nums[i] + next[1][0];
finalAns = max(finalAns, currAns);
for (int parity = 0; parity < 2; parity++) {
for (int isDel = 0; isDel < 2; isDel++) {
long long val = 0;
// It can stop here with the help of 0, if future goes negative
long long ans = 0;
if (parity == 0) {
val = 1LL * nums[i];
} else {
val = -1LL * nums[i];
}
// Include in subarray
long long include = val + next[1 - parity][isDel];
ans = max(ans, include);
// Exclude in subarray
if (isDel == 0) {
long long exclude = next[parity][1];
ans = max(ans, exclude);
}
curr[parity][isDel] = ans;
}
}
// Updation
swap(next, curr);
}
return finalAns;
}
long long maxAlternatingSum(vector<int>& nums) {
// Memoization
// const int size = nums.size();
// long long ans = LLONG_MIN;
// vector<vector<vector<long long>>> dp(size, vector<vector<long long>>(2, vector<long long>(2, LLONG_MIN)));
// for (int i = 0; i < size; i++) {
// // Since we do a 0 at nums.size(), single element can be skipped and also
// long long curr = nums[i] + maxAlternatingSumMemo(i + 1, 1, 0, nums, dp);
// ans = max(ans, curr);
// }
// return ans;
// Tabulation
// return maxAlternatingSumTab(nums);
// Tabulation SO
return maxAlternatingSumTabSO(nums);
}
// 4073. Count Good Strings,
// 2333. Minimum Sum of Squared Difference, Priority Queue
long long minSumSquareDiff(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {
const int n = nums1.size();
const int limit = 1'00'000 + 1;
int k = k1 + k2;
vector<int> mp(limit);
priority_queue<int> pq;
for (int i = 0; i < n; i++) {
const int diff = abs(nums1[i] - nums2[i]);
// No need
if (diff == 0) continue;
// Priority Queue single push
if (mp[diff] == 0) {
pq.push(diff);
}
// Frequency of diff
mp[diff]++;
}
while (!pq.empty() && k > 0) {
const int diff = pq.top();
const int freq = mp[diff];
// Can erase diff
if (k >= freq) {
k -= freq;
// Remove from pq and set mp to 0
pq.pop();
mp[diff] = 0;
// If only diff - 1 never exists && is greater than 0
if (diff > 1 && (pq.empty() || pq.top() != diff - 1)) {
pq.push(diff - 1);
}
// Adding reduced frquencies to diff - 1
mp[diff - 1] += freq;
} else {
// Reducing what we can
mp[diff] -= k;
// Adding reduced frquencies to diff - 1
if (diff > 1) {
mp[diff - 1] += k;
}
k = 0;
}
}
// Final answer
long long ans = 0;
for (int i = 0; i < limit; i++) {
ans += (1LL * i * i * mp[i]);
}
return ans;
}
// Biweekly Contest 193
// 4074. Maximum Product Pair With Target Sum, Map
vector<int> maxProductPair(vector<int>& nums, int target) {
constexpr int shift = 200;
const int size = nums.size();
int l = -1;
int r = -1;
int maxi = INT_MIN;
vector<int> mp(501, -1);
for (int i = 0; i < size; i++) {
const int diff = target - nums[i];
// Present in mp && product is greater
if (mp[diff + shift] != -1 && maxi < diff * nums[i]) {
if (diff > nums[i]) {
r = mp[diff + shift];
l = i;
maxi = diff * nums[i];
} else if (diff < nums[i]) {
r = i;
l = mp[diff + shift];
maxi = diff * nums[i];
}
}
mp[nums[i] + shift] = i;
}
return {r, l};
}
// 4075, 4076. Longest Resilient Subarray I & II, Sliding Window, Factors & Mod
int resilientSubarray(vector<int>& nums, int k) {
const int size = nums.size();
int l = 0;
int r = 1;
int ans = 1;
nums[0] %= k;
int rem = nums[0];
int sum = nums[0];
// The core idea is to get n + 1 of factors of k
// Eg.: If its 18 and we have 9s (18 = 9 * 2, so n is 2) -> 9 + 9 + 9, even if any one of 9 is removed we still get 18
// This also hold true for 2n + 1, 3n + 1, etc. as we have to remove only 1 each time
// Since we need a subarray use sliding window
while (r < size) {
// For overflow
nums[r] %= k;
// Sum if for factor like for 18 it can be 9 + 9
// Hold for subarray of single digit as well
sum = (sum + nums[r]) % k;
// Different rem not applicable, so window resets to size 1
if (nums[r] != rem) {
rem = nums[r];
sum = rem;
l = r;
} else {
// n + 1 design
// If sum == 0 i.e we are at n, we need sum = rem -> (0 + rem) -> (n + 1)
if (sum == rem) {
ans = max(ans, r - l + 1);
}
}
r++;
}
return ans;
}
// 4077. Minimize Inversions in a Prefix Tree, Trie & DP
// Weekly Contest 523
// 4078. Three Fibonacci Sum, Fibonacci Series
bool threeFibonacciSum(int n) {
int a = 0;
int b = 1;
int c = 1;
// Fibonacci Series
while (c < n) {
if (a + b + c == n) return true;
int temp = b + c;
a = b;
b = c;
c = temp;
}
return false;
}
// 4079. Prime Subset Selection I, Sieve method for primes & Greedy
vector<int> maxPrimes(int n, int s) {
// Sieve method
vector<bool> isPrime(n + 1, true);
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
// Since we need to maximise primes, we take greedy approach of taking the smallest primes
// We keep sum to track of sum <= s
int sum = 0;
vector<int> ans;
ans.reserve(n);
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
sum += i;
if (sum > s) break;
ans.push_back(i);
}
}
return ans;
}
// 4080. Design Bus Seat Booking System, System Design
class BusBooking {
public:
int seatsBooked;
int totalTime;
vector<vector<int>> booked;
BusBooking(int n) {
this->seatsBooked = 0;
this->totalTime = 0;
this->booked = vector<vector<int>>(n + 1, vector<int>(4, 0));
}
void toggle(string seat) {
int seatAlpha = seat[0] - 'A';
int seatNum = stoi(seat.substr(1));
// Already booked, substract the time costed
if (booked[seatNum][seatAlpha] != 0) {
seatsBooked--;
totalTime -= booked[seatNum][seatAlpha];
booked[seatNum][seatAlpha] = 0;
} else {
// Check the middle seats for seat 'A' and 'D'
if ( (seatAlpha == 0 && booked[seatNum][seatAlpha + 1] != 0) || (seatAlpha == 3 && booked[seatNum][seatAlpha - 1] != 0) ) {
seatsBooked++;
totalTime += 3;
booked[seatNum][seatAlpha] = 3;
} else {
seatsBooked++;
totalTime++;
booked[seatNum][seatAlpha] = 1;
}
}
}
int getTotalTime() {
return totalTime;
}
// For minimum time, we book all the window seats first and then middle seats
// All booking costs minimum of 1 second
// So, its basically the number of seats booked
int getMinTime() {
return seatsBooked;
}
};
// 4081. Prime Subset Selection II, Sieve method for primes
vector<int> maxPrimeSubset(int n, int s) {
// Edge Case
if (s == 1) return {};
// Sieve Method
vector<bool> isPrime(n + 1, true);
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
// Storing all primes
vector<int> primes;
primes.reserve(n);
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.push_back(i);
}
}
constexpr int INF = 1'000'000'000;
const int size = primes.size();
// DP is minimum number of elements required to make the sum and if it is possible to max such sum
vector<int> dp(s + 1, INF);
dp[0] = 0;
// Choice is if the prime number will help to make the sum
vector<vector<bool>> choice(size, vector<bool>(s + 1, false));
// Bottom-Up
for (int i = size - 1; i >= 0; i--) {
const int val = primes[i];
for (int sum = s; sum >= val; sum--) {
// This will contribute to making of sum
// Every state won't be calculated as INF >= INF + 1 will also happen
if (dp[sum] >= dp[sum - val] + 1) {
// Minimising number of elements to make sum
dp[sum] = dp[sum - val] + 1;
// primes[i] is a candidate to make sum
choice[i][sum] = true;
}
}
}
// Calulating maximum sum, we have handle s == 1 case, so maxiSum will always give us atleast 2
int maxiSum = s;
while (dp[maxiSum] == INF) maxiSum--;
vector<int> ans;
for (int i = 0; i < size; i++) {
if (choice[i][maxiSum]) {
ans.push_back(primes[i]);
// The next choice
maxiSum -= primes[i];
}
}
return ans;
}
// 2778. Sum of Squares of Special Elements, Array
int sumOfSquares(vector<int>& nums) {
const int n = nums.size();
int sumOfSq = 0;
for (int i = 1; i <= n; i++) {
if ((n % i) == 0) {
sumOfSq += (nums[i - 1] * nums[i - 1]);
}
}
return sumOfSq;
}
// 2897. Apply Operations on Array to Maximize Sum of Squares, Bit Manipulation & Greedy
int maxSum(vector<int>& nums, int k) {
constexpr long long MOD = 1'000'000'007;
array<int, 32> bits;
// All set-bits
for (int val: nums) {
int pos = 0;
while (val > 0) {
if ((val & 1) == 1) {
bits[pos]++;
}
val >>= 1;
pos++;
}
}
// Max number of set-bit
int maxCnt = 0;
for (int i = 0; i < 32; i++) {
maxCnt = max(maxCnt, bits[i]);
}
// Forming the largest numbers possible
long long ans = 0;
while (maxCnt-- > 0 && k-- > 0) {
long long val = 0;
for (int i = 0; i < 32; i++) {
if (bits[i] > 0) {
val += (1 << i);
bits[i]--;
}
}
ans = (ans + (val * val)) % MOD;
}
return (int) ans;
}
// 3727. Maximum Alternating Sum of Squares, Sorting & Two-Pointers
long long maxAlternatingSum(vector<int>& nums) {
const int n = nums.size();
// Making all positives
for (int i = 0; i < n; i++) {
if (nums[i] < 0) {
nums[i] = -nums[i];
}
}
// Sorting
sort(nums.begin(), nums.end());
int l = 0;
int r = n - 1;
long long ans = 0;
// Alterating sum l for odd and r for even
while (l < r) {
ans += (nums[r] * nums[r]);
r--;
ans -= (nums[l] * nums[l]);
l++;
}
// n is odd
if (l == r) {
ans += (nums[r] * nums[r]);
}
return ans;
}
// 3723. Maximize Sum of Squares of Digits, Math
string maxSumOfSquares(int num, int sum) {
// Base Case
if (num * 9 < sum) return "";
// mul is number of times we choose 9
int mul = sum / 9;
// After taking all the the 9s, the remaining sum
char rem = (sum % 9) + '0';
string ans = "";
ans.reserve(num);