without considering every opportunity other than the first 20+ and the maximum and minimum values:
My expectation
The first 12 entries in arr [] are precomputed to reduce the recursion depth, but the dollar value does not match the calculated value for these first 12 entries.
for coin values <= 49999, check if the value has already been calculated, if then you do not split the coin into values / 2/3/4 and repeat each of these resulting values.
This limit value (49999) can be increased to 100000, since this is the available size of the arr [] array.
presetting and saving to the arr [] array will help reduce execution time and recursion depth.
using an array so that any previously calculated values (in published code up to 49999) can be immediately returned by the max() function without further recursion.
I would modify the code a bit for better documentation and reliability and faster execution as follows:
#include <stdio.h> #include <stdint.h> #define MAX_ARRAY_LEN (100000) uint32_t arr[ MAX_ARRAY_LEN ] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; uint32_t max(uint32_t n) { if(n < MAX_ARRAY_LEN) { // value of 'n' within the range of the learning array arr[] if(!arr[n] && n) { // then learning array arr[] not yet set return arr[n] = max(n/2) + max(n/3) + max(n/4); } else { // else learning array arr[] already set for 'this' value of 'n' return arr[n]; } } else { // value of 'n' is greater than the learning array arr[] return max(n/2) + max(n/4) + max(n/3); } } // end function: max int main( void ) { uint32_t n; int status; while( (status = scanf("%u", &n)) == 1 && EOF != status) { if( 1000000000 >= n) { printf("%u\n", max(n) ); } else { printf(" invalid value entered, must be in the range 0...1 000 000 000\n"); } // end if } // end while return 0; } // end function: main
source share