-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdp.h
1439 lines (1275 loc) · 40.3 KB
/
dp.h
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
//
// Created by Wei on 2/11/24.
//
#ifndef NEETCODE150_DP_H
#define NEETCODE150_DP_H
#include "common.h"
//70. Climbing Stairs
class Solution70 {
public:
int climbStairs(int n) {
int pre = 1;
int cur = 1;
for (int i=2; i<=n; i++) {
pre += cur;
swap(pre, cur);
}
return cur;
}
};
//509. Fibonacci Number
class Solution509 {
public:
int fib(int N) {
if (N<2)
return N;
int pre= 0;
int cur = 1;
for (int i=2; i<=N; i++) {
pre+=cur;
swap(pre,cur);
}
return cur;
}
};
//1137. N-th Tribonacci Number
class Solution1137 {
public:
int tribonacci(int n) {
vector<int> ans = {0,1,1};
if (n<3)
return ans[n];
for (int i=3; i<=n; i++) {
tie(ans[0], ans[1], ans[2]) = make_tuple(ans[1], ans[2], ans[0]+ans[1]+ans[2]);
}
return ans[2];
}
};
//746. Min Cost Climbing Stairs
class Solution746 {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
int pre = 0;
int cur = 0;
for (int i=2; i<=n; i++) {
pre = min(pre + cost[i-2], cur + cost[i-1]);
swap(pre, cur);
}
return cur;
}
};
//198. House Robber
class Solution198 {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if (n == 0)
return 0;
if (n == 1)
return nums[0];
int pre = nums[0];
int cur = max(nums[1], nums[0]);
for (int i=2; i<n; i++) {
pre = max(pre + nums[i], cur);
swap(pre, cur);
}
return cur;
}
};
//213. House Robber II
class Solution213 {
public:
int rob_base(vector<int>::iterator begin, vector<int>::iterator end) {
int left = 0;
int right = 0;
for (auto itor = begin; itor<end; itor++) {
left = max(left + *itor, right);
swap(left, right);
}
return right;
}
int rob(vector<int>& nums) {
int length = nums.size();
if (length==0)
return 0;
if (length == 1)
return nums[0];
return max(rob_base(nums.begin(), nums.end()-1), rob_base(nums.begin()+1, nums.end()));
}
};
//740. Delete and Earn
class Solution740 {
public:
int deleteAndEarn(vector<int>& nums) {
int n = *max_element(nums.begin(), nums.end());
vector<int> trans(n+1, 0);
for (auto &num: nums) {
trans[num] += num;
}
int pre = trans[0];
int cur = trans[1];
for (int i=2; i<=n; i++) {
pre = max(pre + trans[i], cur);
swap(pre, cur);
}
return cur;
}
};
//5. Longest Palindromic Substring
class Solution5 {
public:
string longestPalindrome(string s) {
if (s.empty())
return "";
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n));
string ans;
for (int distance=0; distance<n; distance++) {
for (int left=0; left+distance<n; left++) {
int right = left+distance;
if (distance==0){
dp[left][right] = true;
}
else if (distance==1) {
dp[left][right] = (s[left]==s[right]);
}
else {
dp[left][right] = (dp[left+1][right-1] && s[left]==s[right]);
}
if (dp[left][right] && distance+1>ans.size()) {
ans = s.substr(left, distance+1);
}
}
}
return ans;
}
};
//647. Palindromic Substrings
class Solution647 {
public:
int countSubstrings(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n));
int total = 0;
for (int distance=0; distance<n; distance++) {
for (int left=0; left+distance<n; left++) {
int right=left+distance;
if (distance==0){
dp[left][right] = true;
}
else if (distance==1) {
dp[left][right] = (s[left]==s[right]);
}
else {
dp[left][right] = (dp[left+1][right-1] && s[left]==s[right]);
}
if (dp[left][right])
total++;
}
}
return total;
}
};
//91. Decode Ways
class Solution91 {
public:
int numDecodings(string s) {
if (s[0] == '0') {
return 0;
}
int n = s.size();
vector<int> dp(n + 1);
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
int ones = stoi(s.substr(i - 1, 1));
if (ones >= 1 && ones <= 9) {
dp[i] += dp[i - 1];
}
int tens = stoi(s.substr(i - 2, 2));
if (tens >= 10 && tens <= 26) {
dp[i] += dp[i - 2];
}
}
return dp[n];
}
};
//322. Coin Change
class Solution322 {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1, amount + 1);
dp[0] = 0;
for (int i=0; i<amount + 1; i++) {
for (int j=0; j<coins.size(); j++) {
if (i >= coins[j])
dp[i] = min(dp[i], dp[i-coins[j]] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};
//152. Maximum Product Subarray
/*
1.If the previous part of the array had a big positive product, adding the current number might make it even bigger.
2.it's better to start a new subarray with just the current number if it's large enough on its own.
3.If the previous subarray had a negative product, multiplying it with the current number might make it the largest positive product.
*/
class Solution152 {
public:
int maxProduct(vector<int>& nums) {
vector<int> maxans(nums), minans(nums);
for (int i=1; i<nums.size(); i++) {
maxans[i] = max(maxans[i-1] * nums[i], max(nums[i], minans[i-1]* nums[i]));
minans[i] = min(maxans[i-1] * nums[i], min(nums[i], minans[i-1]* nums[i]));
}
return *max_element(maxans.begin(), maxans.end());
}
};
//139. Word Break
class Solution139 {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
vector<bool> dp(n+1, false);
dp[0] = true;
unordered_set<string> words(wordDict.begin(), wordDict.end());
for (int i=1; i<=n; i++) {
for (int j=i-1; j>=0; j--) {
if (dp[j] && words.count(s.substr(j, i-j))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
};
//300. Longest Increasing Subsequence
class Solution300 {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n,1);
for (int i=0; i<n; i++) {
for (int j=0; j<i; j++) {
if (nums[i] > nums[j])
dp[i] = max(dp[i], dp[j] + 1);
}
}
return *max_element(dp.begin(), dp.end());
}
};
//673. Number of Longest Increasing Subsequence
class Solution673 {
public:
int findNumberOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, 1);
vector<int> count(n, 1);
for (int i=1; i<n; i++) {
for (int j=0; j<i; j++) {
if (nums[j] < nums[i]) {
if (dp[j]+1 > dp[i]) {
dp[i] = dp[j] + 1;
count[i] = count[j];
} else if (dp[j]+1 == dp[i]) {
count[i] += count[j];
}
}
}
}
int maxlen = *max_element(dp.begin(), dp.end());
int ans = 0;
for (int i=0; i<n; i++) {
if (dp[i]==maxlen)
ans +=count[i];
}
return ans;
}
};
//416. Partition Equal Subset Sum
class Solution416 {
public:
bool canPartition(vector<int>& nums) {
int n = nums.size();
int sum = accumulate(nums.begin(), nums.end(), 0);
if (sum & 1) {
return false;
}
sum >>= 1;
bitset<10000> dp;
dp.set(0);
for (int i = 0; i < n; i++) {
int num = nums[i];
for (int j = sum; j >= num; --j) {
if (dp[j-num]) {
dp.set(j);
}
}
}
return dp[sum];
}
};
//120. Triangle
class Solution120 {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
// Initialize DP array with the values of the last row
for (int i = 0; i < n; ++i) {
dp[n - 1][i] = triangle[n - 1][i];
}
// Bottom-up approach to calculate minimum path sum
for (int i = n - 2; i >= 0; --i) {
for (int j = 0; j <= i; ++j) {
dp[i][j] = triangle[i][j] + min(dp[i + 1][j], dp[i + 1][j + 1]);
}
}
// Minimum path sum will be stored at the top of the DP array
return dp[0][0];
}
};
//256. Paint House
/*
There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
Example:
Input: [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Minimum cost: 2 + 5 + 3 = 10.
*/
class Solution256 {
public:
int minCost(vector<vector<int>>& costs) {
int r = 0, g = 0, b = 0;
for (auto& cost : costs) {
int _r = r, _g = g, _b = b;
r = min(_g, _b) + cost[0];
g = min(_r, _b) + cost[1];
b = min(_r, _g) + cost[2];
}
return min(r, min(g, b));
}
};
//377. Combination Sum IV
class Solution377 {
public:
int combinationSum4(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
//the dp can not be declared as vector<int> or vector<long long>,
//because signed integers overflow is undefined behavior, while unsigned integers wrap around and is well defined.
vector<unsigned int> dp(target + 1);
dp[0] = 1;
for (int i = 1; i <= target; i++) {
for (int& num : nums) {
if (num <= i ) {
dp[i] += dp[i - num];
}
else
break;
}
}
return dp[target];
}
};
//279. Perfect Squares
class Solution279 {
public:
int numSquares(int n) {
vector<int> PerfectSquares;
for (int i = 1; i * i <= n; i++)
{
PerfectSquares.push_back(i * i);
}
int Max = n + 1;
vector<int> dp(n + 1, Max);
dp[0] = 0;
for (int i = 1; i <= n; i++)
{
for (auto &square: PerfectSquares)
{
if (i >= square)
{
dp[i] = min(dp[i], dp[i - square] + 1);
}
}
}
return dp[n] > n ? -1 : dp[n];
}
};
//2369. Check if There is a Valid Partition For The Array
class Solution2369 {
public:
bool validPartition(vector<int>& nums) {
int n = nums.size();
if (n < 2) return false;
vector<bool> dp(n, false);
// Case for two equal elements
if (nums[0] == nums[1]) dp[1] = true;
for (int i = 2; i < n; ++i) {
// Check for partition ending with two equal elements
if (nums[i] == nums[i - 1]) {
dp[i] = dp[i] || dp[i - 2];
}
// Check for partition ending with three equal elements
if (i >= 2 && nums[i] == nums[i - 1] && nums[i] == nums[i - 2]) {
dp[i] = dp[i] || (i >= 3 ? dp[i - 3] : true);
}
// Check for partition ending with three consecutive increasing elements
if (i >= 2 && nums[i] == nums[i - 1] + 1 && nums[i] == nums[i - 2] + 2) {
dp[i] = dp[i] || (i >= 3 ? dp[i - 3] : true);
}
}
return dp[n - 1];
}
};
//1856. Maximum Subarray Min-Product
class Solution1856 {
public:
int maxSumMinProduct(vector<int>& nums) {
int n = nums.size();
vector<long long> prefix(n + 1, 0);
for (int i = 0; i < n; ++i) {
prefix[i + 1] = prefix[i] + nums[i];
}
// Monotonic stack to find left boundaries
vector<int> left(n, -1);
stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && nums[st.top()] >= nums[i]) {
st.pop();
}
if (!st.empty()) {
left[i] = st.top();
}
st.push(i);
}
// Clear the stack to reuse for right boundaries
while (!st.empty()) {
st.pop();
}
// Monotonic stack to find right boundaries
vector<int> right(n, n);
for (int i = n - 1; i >= 0; --i) {
while (!st.empty() && nums[st.top()] >= nums[i]) {
st.pop();
}
if (!st.empty()) {
right[i] = st.top();
}
st.push(i);
}
long long maxMinProduct = 0;
for (int i = 0; i < n; ++i) {
long long sum = prefix[right[i]] - prefix[left[i] + 1];
long long minProduct = nums[i] * sum;
maxMinProduct = max(maxMinProduct, minProduct);
}
return maxMinProduct % MOD;
}
};
//983. Minimum Cost For Tickets
class Solution983 {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
vector<int> dp(366, 0);
set<int> travel_days(days.begin(), days.end());
for (int i = 1; i <= 365; ++i) {
if (travel_days.find(i) == travel_days.end()) {
dp[i] = dp[i - 1];
} else {
dp[i] = min({
dp[i - 1] + costs[0],
dp[max(i - 7, 0)] + costs[1],
dp[max(i - 30, 0)] + costs[2]
});
}
}
return dp[365];
}
};
//343. Integer Break
class Solution343 {
public:
int integerBreak(int n) {
vector<int> dp(n+1);
dp[1] = 1;
for (int i=2; i<=n; i++) {
for (int j = 1; j < i ; j++) {
dp[i] = max(dp[i], max(j * (i-j), j * dp[i-j]));
}
}
return dp[n];
}
};
//691. Stickers to Spell Word
class Solution691 {
public:
int minStickers(vector<string>& stickers, string target) {
int n = target.size();
int targetMask = (1 << n) - 1;
vector<unordered_map<char, int>> stickerCount(stickers.size());
for (int i = 0; i < stickers.size(); ++i) {
for (char c : stickers[i]) {
stickerCount[i][c]++;
}
}
vector<int> dp(1 << n, -1);
dp[0] = 0;
queue<int> q;
q.push(0);
while (!q.empty()) {
int mask = q.front();
q.pop();
for (int i = 0; i < stickers.size(); ++i) {
int newMask = mask;
auto &count = stickerCount[i];
vector<int> remainingCount(26, 0);
for (int j = 0; j < n; ++j) {
if ((mask >> j) & 1) continue;
char c = target[j];
if (count.find(c) != count.end() && count[c] > remainingCount[c - 'a']) {
newMask |= (1 << j);
remainingCount[c - 'a']++;
}
}
if (dp[newMask] == -1 || dp[newMask] > dp[mask] + 1) {
dp[newMask] = dp[mask] + 1;
q.push(newMask);
}
}
}
return dp[targetMask];
}
};
//1035. Uncrossed Lines
class Solution1035 {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
// DP table where dp[i][j] represents the LCS of nums1[0..i-1] and nums2[0..j-1]
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
// Fill the DP table
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// The result is in dp[m][n]
return dp[m][n];
}
};
//2140. Solving Questions With
class Solution2140 {
public:
long long mostPoints(vector<vector<int>>& questions) {
int n = questions.size();
vector<long long> dp(n + 1, 0);
for (int i = n - 1; i >= 0; --i) {
int points = questions[i][0];
int brainpower = questions[i][1];
dp[i] = max(points + (i + brainpower + 1 < n ? dp[i + brainpower + 1] : 0), dp[i + 1]);
}
return dp[0];
}
};
//2466. Count Ways To Build Good Strings
class Solution2466 {
public:
int countGoodStrings(int low, int high, int zero, int one) {
vector<int> dp(high + 1, 0);
dp[0] = 1; // There is one way to form an empty string.
for (int length = 0; length <= high; ++length) {
if (dp[length] > 0) {
if (length + zero <= high) {
dp[length + zero] = (dp[length + zero] + dp[length]) % MOD;
}
if (length + one <= high) {
dp[length + one] = (dp[length + one] + dp[length]) % MOD;
}
}
}
int result = 0;
for (int length = low; length <= high; ++length) {
result = (result + dp[length]) % MOD;
}
return result;
}
};
//837. New 21 Game
class Solution837 {
public:
double new21Game(int n, int k, int maxPts) {
if (k == 0 || n >= k + maxPts) {
return 1.0;
}
vector<double> dp(n + 1, 0.0);
dp[0] = 1.0;
double windowSum = 1.0, result = 0.0;
for (int i = 1; i <= n; ++i) {
dp[i] = windowSum / maxPts;
if (i < k) {
windowSum += dp[i];
} else {
result += dp[i];
}
if (i - maxPts >= 0) {
windowSum -= dp[i - maxPts];
}
}
return result;
}
};
//1626. Best Team With No Conflicts
class Solution1626 {
public:
int bestTeamScore(vector<int>& scores, vector<int>& ages) {
int n = scores.size();
vector<pair<int, int>> players(n);
for (int i = 0; i < n; ++i) {
players[i] = {ages[i], scores[i]};
}
// Sort players by age, and then by score
sort(players.begin(), players.end());
// Initialize dp array
vector<int> dp(n, 0);
int maxScore = 0;
for (int i = 0; i < n; ++i) {
dp[i] = players[i].second; // The score of the player itself
for (int j = 0; j < i; ++j) {
// No conflict if scores[j] <= scores[i]
if (players[j].second <= players[i].second) {
dp[i] = max(dp[i], dp[j] + players[i].second);
}
}
maxScore = max(maxScore, dp[i]);
}
return maxScore;
}
};
//1406. Stone Game III
class Solution1406 {
public:
string stoneGameIII(vector<int>& stoneValue) {
int n = stoneValue.size();
vector<int> dp(n + 1, 0);
for (int i = n - 1; i >= 0; --i) {
int maxScore = INT_MIN;
int curScore = 0;
for (int k = 1; k <= 3 && i + k <= n; ++k) {
curScore += stoneValue[i + k - 1];
maxScore = max(maxScore, curScore - dp[i + k]);
}
dp[i] = maxScore;
}
if (dp[0] > 0) {
return "Alice";
} else if (dp[0] < 0) {
return "Bob";
} else {
return "Tie";
}
}
};
//1964. Find the Longest Valid Obstacle Course at Each Position
class Solution1964 {
public:
vector<int> longestObstacleCourseAtEachPosition(vector<int>& obstacles) {
int n = obstacles.size();
vector<int> dp(n);
// Vector to store the indices of the obstacles in the longest increasing subsequence
vector<int> lis;
for (int i = 0; i < n; ++i) {
auto it = upper_bound(lis.begin(), lis.end(), obstacles[i]);
dp[i] = it - lis.begin() + 1;
if (it == lis.end()) {
lis.push_back(obstacles[i]);
} else {
*it = obstacles[i];
}
}
return dp;
}
};
//1359. Count All Valid Pickup and Delivery Options
/*Intuition:
The total number of all permutation obviously eauqls to 2n!.
For each pair, the order is determined, so we need to divide by 2.
So the final result is (2n)!/(2^n)
*/
class Solution1359 {
public:
int countOrders(int n) {
vector<int> dp(n + 1);
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
// factorial(2n) = 2n * (2n - 1) * factorial(2(n-1))
dp[i] = (static_cast<long long>(dp[i - 1]) * i * (2 * i - 1)) % MOD;
}
return dp[n];
}
};
/************************************2-D dynamic programming********************************/
//62. Unique Paths
class Solution62 {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 1));
for (int i=1; i<m; i++) {
for (int j=1; j<n; j++) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
//63. Unique Paths II
class Solution63 {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> dp(m, vector<int>(n,0));
for (int i=0; i<m; i++) {
if (obstacleGrid[i][0])
break;
dp[i][0] = 1;
}
for (int i=0; i<n; i++) {
if (obstacleGrid[0][i])
break;
dp[0][i] = 1;
}
for (int i=1; i<m; i++) {
for (int j=1; j<n; j++) {
if (obstacleGrid[i][j])
continue;
if (!obstacleGrid[i-1][j])
dp[i][j] += dp[i-1][j];
if (!obstacleGrid[i][j-1])
dp[i][j] += dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
//1143. Longest Common Subsequence
class Solution1143 {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.length();
int n= text2.length();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
for (int i=1; i<=m; i++) {
for (int j=1; j<=n; j++) {
if (text1[i-1] == text2[j-1])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return dp[m][n];
}
};
//516. Longest Palindromic Subsequence
class Solution516 {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
for (int length=0; length<n; length++) {
for (int left=0; left+length<n; left++) {
int right=left+length;
if (length==0) {
dp[left][right]=1;
}
else if (s[left]==s[right]) {
if (length==1)
dp[left][right] = 2;
else
dp[left][right] = dp[left+1][right-1] + 2;
}
else {
dp[left][right] = max(dp[left][right-1], dp[left+1][right]);
}
}
}
return dp[0][n-1];
}
};
//1049. Last Stone Weight II
class Solution1049 {
public:
int lastStoneWeightII(vector<int>& stones) {
int totalWeight = accumulate(stones.begin(), stones.end(), 0);
// Target weight is to try splitting stones into two groups with equal weight
int targetWeight = totalWeight >> 1;
vector<int> dp(targetWeight + 1, 0);
// DP approach to find the closest sum to the targetWeight
for (auto& stone : stones) {
// Traverse dp array backwards for this pass, to avoid using a stone twice
for (int j = targetWeight; j >= stone; --j) {
// Update dp[j] to the higher of the two values;
// either the current dp[j] or the sum of stone and dp[j - stone] if we include the stone
dp[j] = max(dp[j], dp[j - stone] + stone);
}
}
// The answer is the total weight minus twice the optimized closest sum to half of the total weight
// This represents the minimal possible weight difference between two groups
return totalWeight - dp[targetWeight] * 2;
}
};
//309. Best Time to Buy and Sell Stock with Cooldown
class Solution309 {
public:
int maxProfit(vector<int>& prices) {
int buy = -prices[0], sell = 0, lock = 0;
for (auto& p : prices)
{
buy = max(buy, lock - p);
lock = max(sell, buy + p);
swap(lock, sell);
}
return sell;
}
};
//877. Stone Game
class Solution877 {
public:
bool stoneGame(vector<int>& piles) {
int n = piles.size();
vector<vector<int>> dp(n+1, vector<int>(n+1));
for (int len = 0; len < n; len++) {
for (int left = 0; left+len < n; left++) {
if (len == 0) {
dp[left][left] = piles[left];
continue;
}
int right = left + len;
dp[left][right] = max(piles[left] - dp[left+1][right], piles[right] - dp[left][right-1]);
}
}
return dp[0][n-1] > 0;
}
};
//64. Minimum Path Sum
class Solution64 {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> dp(n, vector<int>(m));
dp[0][0] = grid[0][0];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 && j == 0) {
continue;
}
dp[i][j] = grid[i][j] + min( ((i>0) ? dp[i-1][j] : INT_MAX),
((j>0) ? dp[i][j-1] : INT_MAX));
}
}
return dp[n-1][m-1];
}
};
//329. Longest Increasing Path in a Matrix
class Solution329 {