-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem45.c
More file actions
99 lines (78 loc) · 2.18 KB
/
problem45.c
File metadata and controls
99 lines (78 loc) · 2.18 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
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define INITIAL_SIZE 10
#define MAX_ROOM_JUMP 10000
typedef struct {
int index;
int value;
} Pair;
void getPointsArray(int **arr, int *count) {
int size = INITIAL_SIZE;
*count = 0;
int num = 0, ch, reading = 0;
*arr = malloc(size * sizeof(int));
if (!(*arr)) {
printf("Memory allocation failed.\n");
exit(1);
}
printf("Enter room values (space-separated, press Enter to finish):\n");
while ((ch = getchar()) != '\n') {
if (isdigit(ch) || (ch == '-' && !reading)) {
ungetc(ch, stdin);
scanf("%d", &num);
reading = 1;
if (*count >= size) {
size *= 2;
int *temp = realloc(*arr, size * sizeof(int));
if (!temp) {
printf("Memory reallocation failed.\n");
free(*arr);
exit(1);
}
*arr = temp;
}
(*arr)[(*count)++] = num;
} else {
reading = 0;
}
}
}
void getMaxRoomJump(int *k) {
while (1) {
printf("Enter max number of rooms you can jump (1 to %d): ", MAX_ROOM_JUMP);
scanf("%d", k);
if (*k >= 1 && *k <= MAX_ROOM_JUMP) break;
printf("Invalid input. Try again.\n");
}
}
int getMaxScore(int *arr, int n, int k) {
int *dp = malloc(n * sizeof(int));
if (!dp) {
printf("Memory allocation failed for DP.\n");
return 0;
}
dp[0] = arr[0];
int *dq = malloc(n * sizeof(int));
int front = 0, back = 0;
dq[back++] = 0;
for (int i = 1; i < n; i++) {
if (dq[front] < i - k) front++;
dp[i] = arr[i] + dp[dq[front]];
while (back > front && dp[i] >= dp[dq[back - 1]]) back--;
dq[back++] = i;
}
int result = dp[n - 1];
free(dp);
free(dq);
return result;
}
int main() {
int *rooms = NULL, roomCount = 0, maxJump = 0;
getPointsArray(&rooms, &roomCount);
getMaxRoomJump(&maxJump);
int score = getMaxScore(rooms, roomCount, maxJump);
printf("\nMaximum path score: %d\n", score);
free(rooms);
return 0;
}