-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmax_sum.c
More file actions
72 lines (52 loc) · 1.31 KB
/
max_sum.c
File metadata and controls
72 lines (52 loc) · 1.31 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
/*
Maximum Sum Problem on GeeksForGeeks
Problem Link: https://practice.geeksforgeeks.org/problems/maximum-sum-problem/0
Note: This solution is based on Dynamic Programming (Memoization)
Author: Shyam Kumar
*/
#include <stdio.h>
#include <stdlib.h>
// typedef int unsigned long int;
unsigned long int *lookup;
unsigned long int max( unsigned long int a, unsigned long int b ) {
if( b > a )
return b;
return a;
}
unsigned long int maximum_sum( unsigned long int n ) {
if( lookup[n] == -1 ) {
if( n < 4 )
lookup[n] = n;
else {
lookup[n] = max( n, ( max(n/2, maximum_sum(n/2)) +
max(n/3, maximum_sum(n/3)) + max(n/4, maximum_sum(n/4)) ) );
}
}
return lookup[n];
}
void initialize( unsigned long int n ) {
unsigned long int i;
for( i = 0; i < n; i++ )
lookup[i] = -1;
return;
}
int main(int argc, char const *argv[])
{
int t;
unsigned long int n, ans;
printf("Enter the number of test cases:");
scanf("%d",&t);
while(t--) {
printf("\nEnter the value of n:");
scanf("%lu",&n);
printf("\nn= %lu", n);
/* Dynamically allocating the lookup array */
lookup = (unsigned long int*)malloc( 100000 * sizeof( unsigned long int ) );
/* Initializing the lookup array */
initialize( n+1 );
ans = maximum_sum( n );
printf("\nAns = %lu", ans);
//free(lookup);
}
return 0;
}