-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode-cpp.cpp
1834 lines (1503 loc) · 57.5 KB
/
leetcode-cpp.cpp
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
/*
3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int arr[130],left=0,res=0;
for(int i=0;i<s.length();res=max(res,i-left+1),i++){
arr[s[i]]++;
while(arr[s[i]]>1) arr[s[left++]]--;
}
return res;
}
};
/*
9. Palindrome Number
Given an integer x, return true if x is a palindrome, and false otherwise.
*/
class Solution {
public:
bool isPalindrome(int x) {
string a=to_string(x),b=a;
reverse(b.begin(),b.end());
return a==b;
}
};
/*
85. Maximal Rectangle
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
*/
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
auto A=f(matrix);
int res=0;
for(auto& row:A){
row.push_back(0);
vector<int> stack={-1};
for(int i=0;i<row.size();i++){
while(stack.back()!=-1 && row[stack.back()]>=row[i]){
int val=row[stack.back()];
stack.pop_back();
res=max(res,(i-stack.back()-1)*val);
}
res=max(res,(i-stack.back()-1)*row[i]);
stack.push_back(i);
}
}
return res;
}
vector<vector<int>> f(auto& A){
vector<vector<int>> res(A.size(),vector<int>(A[0].size()));
for(int i=0;i<A.size();i++){
for(int j=0;j<A[0].size();j++){
res[i][j]=A[i][j]-'0';
if(i>0 && res[i][j]){
res[i][j]+=res[i-1][j];
}
}
}
return res;
}
};
/*
147. Insertion Sort List
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
It repeats until no input elements remain.
The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
*/
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* dummy=new ListNode(-1);
while(head!=nullptr){
ListNode* rem=head->next,*beg=dummy,*end=dummy->next;
while(end!=nullptr){
if(end->val > head->val) break;
beg=end;
end=end->next;
}
beg->next=head;
head->next=end;
head=rem;
}
return dummy->next;
}
};
/*
322. Coin Change
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
*/
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int memo[12][10001],res;
memset(memo,-1,sizeof(memo));
sort(coins.begin(),coins.end(),[&](int x,int y){return x>y;});
function<int(int,int)> f=[&](int idx,int rem){
if(rem<=0 || idx==coins.size()){
return rem==0 ? 0:10001;
}
if(memo[idx][rem]==-1){
int res=min(f(idx+1,rem),1+f(idx,rem-coins[idx]));
memo[idx][rem]=res;
}
return memo[idx][rem];
};
res=f(0,amount);
return res>10000 ? -1:res;
}
};
/*
410. Split Array Largest Sum
Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.
Return the minimized largest sum of the split.
A subarray is a contiguous part of the array.
*/
class Solution {
public:
int splitArray(vector<int>& nums, int k) {
int left=*max_element(nums.begin(),nums.end()),right=1e9;
while(left<right){
int mid=(left+right)/2;
if(f(mid,nums,k)) right=mid;
else left=mid+1;
}
return left;
}
bool f(int x,vector<int>& nums,int k){
int parts=0,tot=0;
for(int num:nums){
if((tot+num)<=x){
tot+=num;
}
else{
tot=num;
++parts;
}
}
return (parts+1)<=k;
}
};
/*
424. Longest Repeating Character Replacement
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
*/
class Solution {
public:
int characterReplacement(string s, int k) {
int res=0;
for(char ch:unordered_set<char>(s.begin(),s.end())){
res=max(res,f(ch,k,s));
}
return res;
}
int f(char i,int k,string& s){
int left,res,cur;
for(int j=0;j<s.length();j++){
cur+=(s[j]==i ? 1:0);
while((j-left+1-cur)>k){
cur-=(s[left++]==i ? 1:0);
}
res=max(res,j-left+1);
}
return res;
}
};
/*
632. Smallest Range Covering Elements from K Lists
You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.
*/
class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& nums) {
vector<vector<int>> A;
for(int i=0;i<nums.size();i++){
for(int j:nums[i]){
A.push_back({j,i});
}
}
sort(A.begin(),A.end());
vector<int> cnt(nums.size(),0),res{0,(int)1e6};
for(int l=0,r=0,found=0;r<A.size();r++){
if(++cnt[A[r][1]]==1){
++found;
}
while(cnt[A[l][1]]>1){
--cnt[A[l++][1]];
}
if(found==nums.size() && ((res[1]-res[0])>(A[r][0]-A[l][0]) ||
(A[r][0]-A[l][0])==(res[1]-res[0]) && res[0]>A[l][0])){
res=vector<int>{A[l][0],A[r][0]};
}
}
return res;
}
};
/*
907. Sum of Subarray Minimums
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
*/
class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& nums) {
vector<vector<int>> A;
for(int i=0;i<nums.size();i++){
for(int j:nums[i]){
A.push_back({j,i});
}
}
sort(A.begin(),A.end());
vector<int> cnt(nums.size(),0),res{0,(int)1e6};
for(int l=0,r=0,found=0;r<A.size();r++){
if(++cnt[A[r][1]]==1){
++found;
}
while(cnt[A[l][1]]>1){
--cnt[A[l++][1]];
}
if(found==nums.size() && ((res[1]-res[0])>(A[r][0]-A[l][0]) ||
(A[r][0]-A[l][0])==(res[1]-res[0]) && res[0]>A[l][0])){
res=vector<int>{A[l][0],A[r][0]};
}
}
return res;
}
};
/*
1234. Replace the Substring for Balanced String
You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.
A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.
*/
class Solution {
public:
int balancedString(string s) {
unordered_map<char,int> cnt;
int width=s.length(),tar=s.length()/4,left=0;
for(char& c:s){
cnt[c]++;
}
for(int i=0;i<s.length();i++){
--cnt[s[i]];
while(left<=i && cnt[s[left]]<tar){
cnt[s[left++]]++;
}
if(cnt['Q']<=tar && cnt['W']<=tar && cnt['E']<=tar && cnt['R']<=tar) {
width=min(width,i-left+1);
}
}
return width;
}
};
/*
1458. Max Dot Product of Two Subsequences
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
*/
class Solution {
public:
int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {
long long memo[501][501][2];
memset(memo,-1,sizeof(memo));
function<long long(int,int,int)> f=[&](int i,int j,int k){
if(i==nums1.size() || j==nums2.size()){
return (long long)(k==0 ? INT_MIN:0);
}
if(memo[i][j][k]==-1){
memo[i][j][k]=max(f(i+1,j,k),max(f(i,j+1,k),nums1[i]*nums2[j]+f(i+1,j+1,1)));
}
return memo[i][j][k];
};
return f(0,0,0);
}
};
/*
1462. Course Schedule IV
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.
Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.
Return a boolean array answer, where answer[j] is the answer to the jth query.
*/
class Solution {
public:
vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
vector<vector<int>> tree(numCourses,vector<int>());
vector<unordered_set<int>> res(numCourses,unordered_set<int>());
vector<int> visited(101,0);
for(auto& p:prerequisites){
tree[p[0]].push_back(p[1]);
}
function<unordered_set<int>(int)> f=[&](int node){
if(++visited[node]>1){
return res[node];
}
unordered_set<int> tmp={node};
for(int child:tree[node]){
auto anc=f(child);
tmp.insert(anc.begin(),anc.end());
}
for_each(tmp.begin(),tmp.end(),[&](int i){res[node].insert(i);});
return tmp;
};
for(int i=0;i<numCourses;i++){
if(visited[i]==0) f(i);
}
vector<bool> ans;
transform(queries.begin(),queries.end(),back_inserter(ans),[&](auto& a){
return res[a[0]].count(a[1])>0;
});
return ans;
}
};
/*
1609. Even Odd Tree
A binary tree is named Even-Odd if it meets the following conditions:
The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.
*/
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
class Solution {
public:
bool isEvenOddTree(TreeNode* root) {
deque<TreeNode*> q={root};
int level=0;
while(!q.empty()){
int prev=level%2==0 ? -1:1e8,size=q.size();
for(int i=0;i<size;i++){
TreeNode* node=q.front();q.pop_front();
if(!(node==nullptr)){
if(level%2 == node->val%2) return false;
int dif=node->val-prev;
if(level%2==0 && dif<=0 || level%2==1 && dif>=0) return false;
prev=node->val;
q.push_back(node->left);q.push_back(node->right);
}
}
++level;
}
return true;
}
};
/*
1671. Minimum Number of Removals to Make Mountain Array
You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array nums, return the minimum number of elements to remove to make nums a mountain array.
*/
class Solution {
public:
int minimumMountainRemovals(vector<int>& nums) {
vector<int> A=f(nums);
reverse(nums.begin(),nums.end());
vector<int> B=f(nums);
int res=0;
for(int i=0;i<A.size();i++){
if(A[i]>1 && B[B.size()-i-1]>1){
res=max(res,A[i]+B[B.size()-i-1]);
}
}
return A.size()-res+1;
}
vector<int> f(vector<int>& A){
vector<int> res,B;
for(int i:A){
if(B.empty() || i>B.back()){
B.push_back(i);
res.push_back(B.size());
}
else{
int idx=lower_bound(B.begin(),B.end(),i)-B.begin();
B[idx]=i;
res.push_back(idx+1);
}
}
return res;
}
};
/*
1685. Sum of Absolute Differences in a Sorted Array
You are given an integer array nums sorted in non-decreasing order.
Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.
In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).
*/
class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
int pref=0,suf=accumulate(nums.begin(),nums.end(),0);
vector<int> res;
for(int i=0;i<nums.size();i++){
suf-=nums[i];
res.push_back(i*nums[i]-pref+suf-(nums.size()-i-1)*nums[i]);
pref+=nums[i];
}
return res;
}
};
/*
1712. Ways to Split Array Into Three Subarrays
A split of an integer array is good if:
The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right.
The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right.
Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.
*/
class Solution {
public:
int waysToSplit(vector<int>& nums) {
int tot=nums[0],res=0,mod=1e9+7,n=nums.size();
for(int i=1;i<nums.size();i++){
tot+=nums[i];
nums[i]+=nums[i-1];
}
for(int i=0;i<nums.size();i++){
auto f1=lower_bound(nums.begin()+i+1,nums.end(),nums[i]*2)-nums.begin();
auto f2=upper_bound(nums.begin()+i+1,nums.begin()+n-1,(tot+nums[i])/2)-nums.begin();
res+=f2>f1 ? f2-f1:0;
res%=mod;
}
return res;
}
};
/*
1743. Restore the Array From Adjacent Pairs
There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.
You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.
It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.
Return the original array nums. If there are multiple solutions, return any of them.
*/
class Solution {
public:
vector<int> restoreArray(vector<vector<int>>& A) {
unordered_map<int,vector<int>> B;
vector<int> res;
for(auto& ab:A){
B[ab[0]].push_back(ab[1]);
B[ab[1]].push_back(ab[0]);
}
for(auto& b:B){
if(b.second.size()==1){
res.push_back(b.first);
break;
}
}
while(res.size()<A.size()+1){
int cur=res.back(),nxt=B[cur].back();
B[cur].pop_back();
B[nxt].erase(find(B[nxt].begin(),B[nxt].end(),cur));
res.push_back(nxt);
}
return res;
}
};
/*
1751. Maximum Number of Events That Can Be Attended II
You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend.
You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.
Return the maximum sum of values that you can receive by attending events.
*/
class Solution {
public:
int maxValue(vector<vector<int>>& events, int k) {
sort(events.begin(),events.end());
vector<vector<int>> memo(events.size()+1,vector<int>(k+1,-1));
return f(0,k,events,memo);
}
int f(int idx,int rem,vector<vector<int>>& events,auto& memo){
if(idx==events.size()){
return 0;
}
if(memo[idx][rem]==-1){
auto i = upper_bound(begin(events) + idx, end(events), events[idx][1],
[](int t, const vector<int> &v) {return v[0] > t;}) - begin(events);
int res=f(idx+1,rem,events,memo);
if(rem>0) res=max(res,f(i,rem-1,events,memo)+events[idx][2]);
memo[idx][rem]=res;
}
return memo[idx][rem];
}
};
/*
1755. Closest Subsequence Sum
You are given an integer array nums and an integer goal.
You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).
Return the minimum possible value of abs(sum - goal).
Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
*/
class Solution {
public:
int minAbsDifference(vector<int>& nums, int goal) {
int n=nums.size(),res=INT_MAX;
vector<int> B1,B2,A1(nums.begin(),nums.begin()+n/2),A2(nums.begin()+n/2,nums.end());
f(0,0,A1,B1);
f(0,0,A2,B2);
sort(B1.begin(),B1.end());
sort(B2.begin(),B2.end());
for(int j:B1){
int idx=lower_bound(B2.begin(),B2.end(),goal-j)-B2.begin();
if(idx<B2.size()) res=min(res,abs(goal-B2[idx]-j));
if(idx>0) res=min(res,abs(goal-B2[idx-1]-j));
}
return res;
}
void f(int idx,int cur,vector<int>& A,vector<int>& B){
if(idx==A.size()){
B.push_back(cur);
return;
}
f(idx+1,cur+A[idx],A,B);
f(idx+1,cur,A,B);
}
};
/*
1766. Tree of Coprimes
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.
To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.
Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.
An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.
Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.
*/
class Solution {
public:
vector<int> getCoprimes(vector<int>& nums, vector<vector<int>>& edges) {
vector<vector<int>> A(51,vector<int>());
vector<vector<int>> tree(nums.size(),vector<int>());
vector<vector<pair<int,int>>> pars(51,vector<pair<int,int>>());
for(int i=0;i<=50;i++){
for(int j=0;j<=50;j++){
if(gcd(i,j)==1) A[i].push_back(j);
}
}
for(auto& n:edges){
tree[n[0]].push_back(n[1]);
tree[n[1]].push_back(n[0]);
}
vector<int> res(nums.size(),-1);
function<void(int,int,int)> f=[&](int node,int level,int par){
int val=nums[node],cur_res=-1;
for(int a:A[val]){
if(!pars[a].empty() && pars[a].back().first>cur_res){
cur_res=pars[a].back().first;
res[node]=pars[a].back().second;
}
}
pars[val].push_back({level,node});
for(int child:tree[node]){
if(child==par) continue;
f(child,level+1,node);
}
pars[val].pop_back();
};
f(0,0,-1);
return res;
}
};
/*
1771. Maximize Palindrome Length From Subsequences
You are given two strings, word1 and word2. You want to construct a string in the following manner:
Choose some non-empty subsequence subsequence1 from word1.
Choose some non-empty subsequence subsequence2 from word2.
Concatenate the subsequences: subsequence1 + subsequence2, to make the string.
Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0.
A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters.
A palindrome is a string that reads the same forward as well as backward.
*/
class Solution {
public:
int memo[2][1000][1000],memo2[1000][1000][2];
int longestPalindrome(string w1, string w2) {
memset(memo,-1,sizeof(memo));
memset(memo2,-1,sizeof(memo2));
return pal(w1,w2,0,w2.length()-1,0);
}
int f(string& w1,string& w2,int i,int left,int right){
string& w=(i==0 ? w1:w2);
if (left>right){
return 0;
}
int* A=&memo[i][left][right];
if(*A==-1 && w[left]==w[right]){
*A=f(w1,w2,i,left+1,right-1)+(left==right ? 1:2);
}
if(*A==-1 && w[left]!=w[right]){
*A=max(f(w1,w2,i,left+1,right),f(w1,w2,i,left,right-1));
}
return *A;
}
int pal(string& w1,string& w2,int i,int j,int k){
if(i==w1.length() || j==-1){
return k==1 ? f(w1,w2,0,i,w1.length()-1)+f(w1,w2,1,0,j):0;
}
int* A=&memo2[i][j][k];
if(*A==-1){
if(w1[i]==w2[j]){
*A=2+pal(w1,w2,i+1,j-1,1);
}
else{
*A=max(pal(w1,w2,i+1,j,k),pal(w1,w2,i,j-1,k));
}
}
return *A;
}
};
/*
2009. Minimum Number of Operations to Make Array Continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer.
nums is considered continuous if both of the following conditions are fulfilled:
All elements in nums are unique.
The difference between the maximum element and the minimum element in nums equals nums.length - 1.
For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.
Return the minimum number of operations to make nums continuous.
*/
class Solution {
public:
int minOperations(vector<int>& nums) {
int init=nums.size(),match=0;
sort(nums.begin(),nums.end());
nums.erase(unique(nums.begin(),nums.end()),nums.end());
for(int i=0;i<nums.size();i++){
int idx=lower_bound(nums.begin(),nums.end(),nums[i]+init)-nums.begin();
match=max(match,idx-i);
}
return init-match;
}
};
/*
2030. Smallest K-Length Subsequence With Occurrences of a Letter
You are given a string s, an integer k, a letter letter, and an integer repetition.
Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
*/
class Solution {
public:
string smallestSubsequence(string s, int k, char letter, int r) {
vector<int> A;
int rem=count(s.begin(),s.end(),letter),cur=0;
auto f=[&](int i){
return (A.size()+s.length()-i-1)>=k &&
(rem+cur-(A.back()==letter ? 1:0))>=r && s[i]<A.back();
};
for(int i=0;i<s.length();i++){
while(!A.empty() && f(i)){
cur-=letter==A.back() ? 1:0;
A.pop_back();
}
cur+=letter==s[i] ? 1:0;
rem-=letter==s[i] ? 1:0;
A.push_back(s[i]);
}
string res="";
int take=k-r;
for(int i:A){
if(res.length()==k) break;
if(i==letter || take>0){
take-=i==letter ? 0:1;
res+=i;
}
}
return res;
}
};
/*
2050. Parallel Courses III
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.
You must find the minimum number of months needed to complete all the courses following these rules:
You may start taking a course at any time if the prerequisites are met.
Any number of courses can be taken at the same time.
Return the minimum number of months needed to complete all the courses.
Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).
*/
class Solution {
public:
int minimumTime(int n, vector<vector<int>>& relations, vector<int>& times) {
vector<vector<int>> preq(n+1,vector<int>());
vector<int> rank(n+1,0);
for(auto& a:relations){
preq[a[0]].push_back(a[1]);
++rank[a[1]];
}
priority_queue<array<int,2>,vector<array<int,2>>,greater<>> q;
for(int i=1;i<=n;i++){
if(rank[i]==0) q.push({times[i-1],i});
}
int taken=0,time=0;
while(taken<n){
time=q.top()[0];
while(!q.empty() && q.top()[0]==time){
int course=q.top()[1];
q.pop();
++taken;
for(int m:preq[course]){
--rank[m];
if(rank[m]==0){
q.push({times[m-1]+time,m});
}
}
}
}
return time;
}
};
/*
2163. Minimum Difference in Sums After Removal of Elements
You are given a 0-indexed integer array nums consisting of 3 * n elements.
You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:
The first n elements belonging to the first part and their sum is sumfirst.
The next n elements belonging to the second part and their sum is sumsecond.
The difference in sums of the two parts is denoted as sumfirst - sumsecond.
For example, if sumfirst = 3 and sumsecond = 2, their difference is 1.
Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.
Return the minimum difference possible between the sums of the two parts after the removal of n elements.
*/
class Solution {
public:
long long minimumDifference(vector<int>& nums) {
long long n=nums.size(),a,b,res=LLONG_MAX;
vector<long long> AA(n,0),BB(n,0);
priority_queue<long long> A,B;
for(long long i=0,tot=0;i<2*n/3+1;i++){
tot+=nums[i];
A.push(nums[i]);
if(A.size()>n/3){
tot-=A.top();
A.pop();
}
AA[i]=tot;
}
for(long long i=n-1,tot=0;i>=n/3;i--){
tot+=nums[i];
B.push(-nums[i]);
if(B.size()>n/3){
tot+=B.top();
B.pop();
}
BB[i]=tot;
}
for(int i=n/3-1;i<2*n/3;i++){
res=min(res,AA[i]-BB[i+1]);
}
return res;
}
};
/*
2179. Count Good Triplets in an Array
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].
A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z.
Return the total number of good triplets.
*/
class BIT{
public:
int tree[100001],n;
BIT(int n){
this->n=n;
}
int get(int i,int res=0){
for(i=i+1;i>0;i-=i&(-i)){
res+=tree[i];
}
return res;
}
void add(int val,int x){
for(val=val+1;val<=n;val+=val&(-val)){
tree[val]+=x;
}
}
};
class Solution {
public:
long long goodTriplets(vector<int>& nums1, vector<int>& nums2) {
long long n=nums2.size(),res=0;
BIT left(n),right(n);
vector<int> idx_map(n,0);
for(int i=0;i<n;i++){
idx_map[nums2[i]]=i;
}
for(int i:nums2){
right.add(i,1);
}
for(int i:nums1){
int idx=idx_map[i];
right.add(idx,-1);
int x=left.get(idx-1),y=right.get(n-1)-right.get(idx);
res+=x*y;
left.add(idx,1);
}
return res;
}
};
/*
2246. Longest Path With Different Adjacent Characters
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.