title: I get different value in recursion for knapsack problem
body: <p>I wrote two pieces of code for knapsack problem. The first code gives me the correct answer (which is 16) and the second one doesn't. Is it something wrong with my recursive function?</p>
  
  <p>First code (correct answer):</p>
  
  <pre class="lang-java prettyprint-override"><code>public class knapsackProblem {
  
      static int[] weight = {1,2,4,2,5};
      static int[] value = {5,3,5,3,2};
      int result = 0;
  
      // recursive function
      public int sack(int i, int cap) 
      {
          //base case
          if(i&lt;0 || cap == 0)
          {
              return 0;
          } else if(weight[i] &gt; cap)
          {
              return sack(i-1, cap);
          } else
          {
              //get maximum value
              return Math.max(sack(i-1, cap), value[i] + sack(i-1, cap - weight[i]));
          }
      }
  
      public static void main(String[] args) 
      {
          int capacity = 10;
          int len = weight.length;
          knapsackProblem kp = new knapsackProblem();
          int total = kp.sack(len - 1, capacity);
          System.out.println("sacked array is " + total);
      }
  
  }
  </code></pre>
  
  <p>Second code (incorrect answer):</p>
  
  <pre class="lang-java prettyprint-override"><code>public class knapsackProblem {
  
      static int[] weight = {1,2,4,2,5};
      static int[] value = {5,3,5,3,2};
      int result = 0;
      int tempNO = 0;
      int tempYES = 0;
  
      // recursive function
      public int sack(int i, int cap) 
      {
          //base case
          if(i&lt;0 || cap == 0)
          {
              return 0;
          } else if(weight[i] &gt; cap)
          {
              return sack(i-1, cap);
          } else
          {
              //no case, move on to next value
              tempNO = sack(i-1, cap);
  
              //yes case, add the current value and move on to next value with decreased capacity
              tempYES = value[i] + sack(i-1, cap - weight[i]);
  
              //get maximum value
              return Math.max(tempNO, tempYES);
          }
      }
  
      public static void main(String[] args) 
      {
          int capacity = 10;
          int len = weight.length;
          knapsackProblem kp = new knapsackProblem();
          int total = kp.sack(len - 1, capacity);
          System.out.println("sacked array is " + total);
      }
  
  }
  </code></pre>
  
  <p>The only difference is that in second code I put the results from recursion into variables before comparing for maximum value.</p>
  
  <p>Thanks</p>