-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgame-of-two-stacks-dp.c
More file actions
57 lines (49 loc) · 1017 Bytes
/
game-of-two-stacks-dp.c
File metadata and controls
57 lines (49 loc) · 1017 Bytes
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
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int twoStacks(int maxSum, int a_count, int* a, int b_count, int* b) {
int currSum = 0;
int count = 0;
// add all a's
int i = 0;
while((i<a_count) && (currSum + *(a+i) <= maxSum)) {
currSum += *(a+i);
count++;
i++;
}
i--;
int maxCount = count;
// add b's (and remove a's when needed)
int j = 0;
while(1) {
if(j<b_count && (currSum + *(b+j) <= maxSum)) {
currSum += *(b+j);
count++;
j++;
if (count > maxCount) {
maxCount = count;
}
continue;
} else if(j<b_count && i>=0 && (currSum + *(b+j) > maxSum)) {
currSum -= *(a+i);
count--;
i--;
if (count > maxCount) {
maxCount = count;
}
continue;
} else {
break;
}
}
return maxCount;
}
int main() {
int a[4] = {5, 5, 10, 10};
int b[5] = {9, 9, 1, 1, 5};
printf("%d\n", twoStacks(20, 4, a, 5, b));
int a2[5] = {4, 2, 4, 6, 1};
int b2[4] = {2, 1, 8, 5};
printf("%d\n", twoStacks(10, 5, a2, 4, b2));
return 0;
}