Monday, May 2, 2016

Lets look at a few coding problems:
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

 we can use dynamic programming approach here:
int[] dp = new int[n+1];
for(int i = 1; i<n; i++)
   for(int j=1; j< i+1; j++){
       if (i+j<=n)
          dp[i+j] = Math.max(Math.max(dp[i],i)*Math.max(dp[j],j), dp[i+j]);

return dp[n];

We review a problem we discussed earlier to see another solution
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n]inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.

We said earlier that there is a dynamic programming approach :
If the range of sums that can be generated using the first k numbers in nums is from 0 to r, and the next number has value x, then either:
• x <= r+1 and it is possible to generate any sum from 0 to r+x using the first k+1 numbers, or
• x > r + 1 and it is not possible to generate the sum r + 1, since x and all the following numbers have greater values.
We keep adding x=r+1 and counting such additions until r meets or exceeds n.
We can say this another way. Let x be the smallest number that cannot be formed by the sum of the elements in the array . All elements 0< number < x can be formed. x starts at 1. If the next number is <= x, then the boundary is increased to x+next_number. If the next number is greater than x, then that means there is a gap and we need to insert a number. Inserting x is a choice is then that doubles the boundary and covers every number between the boundaries.
 int GetMinPatches(List<int> nums, int n)
{
int count = 0;
int x = 1;
int I = 0;
while (x < n)
{
     if (I < nums.Count && nums[I] <= x){
         x= x + nums[I];
         I++
        } else{
         x = x+ x;
         count++;
     }
}
return count;
}

No comments:

Post a Comment