简体   繁体   中英

Programming_question on dynamic programming

A company produces a product. The production is done in a very mysterious way. The firm either produces one extra product in a day or they have a power to double the production of products they had on the previous day. Initially they have only 1 product and after some day they have exactly "n" products. You need to find out the minimum days in order to make exactly "n" products. TESTCASE: n = 8 output = 3 explanation: If production is doubled every day, than in three days it is possible to make 1 x 2 x 2 x 2 = 8 products. Few more: For 15 products OUTPUT 6 For 19 products OUTPUT 6

You need to solve this using dynamic programming. For a given n products, start populating from the bottom up manner. Please find the code below with your test cases passing:

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

int main()
{

   int n = -1, i =0, tmp=0;
   // int result = -1;
   printf("\nEnter value: ");
   scanf("%d", &n);

   if (n == -1)
    return -1;


   if(n == 1)
   {
    printf("\nOnly a single day");
    return 0;
   }


   int *arr = malloc(n*sizeof(int));

   for (i=0; i<n; i++)
    arr[i]=INT_MAX;


   arr[0] = 1;

   for(i=1; i<n; i++)
   {
    arr[i] = arr[i-1] + 1;

    if ((i+1)%2 == 0)
    {
        tmp = arr[(i+1)/2 - 1] + 1;
        if (tmp < arr[i])
            arr[i] = tmp;
    }

   }

   printf("\nResult: %d", arr[n-1]-1);
}

Output:

Test Case 1:

Enter value: 8

Result: 3

Test Case 2:

Enter value: 15

Result: 6

Test Case 3:

Enter value: 19

Result: 6

CODE EXPLANATION:

You need to construct an array containing as much number of elements as is the value. For eg. if the value is 8, you need to construct the array having 8 elements. Then you need deal with value 2,3,4 .... till 8. There is no need for value 1 since when you start, the problem states you already have 1 with you. The value in the array elements signify the number of days. The array index is such that index = value -1 .

Your final aim is to get to 8 . But you need to start from bottom up. You need to ask yourself what best you can do (minimum number of days) with value 2 ? It is either the previous element's value +1 (since the problem states you either do day's value = previous day's value + 1 ) or the best that you were doing with value half of the current value plus 1 (the problem states that you can multiply by 2 also the other day). Whichever number is less you assign it to the current value's index. This logic is inside the for loop for each index.

You repeat the steps for 3,4,.... till 8. Now when you reach 8 , the value at the index ( 8-1 ) contain days including the start, therefore you need to subtract 1 and finally display the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM