title: Memoized Rod Cutting Algorithm
body: <p>I'm trying to implement memoized version of recursive rod cutting algorithm. Here is my code (I implemented it from Cormen's pseudo code)</p>
  
  <pre><code>public class simpleMemoized {
  
      //finds maximum of two given integers
      public static int max(int a, int b) {
          return (a &gt; b) ? a : b;
  
      }
  
      public static int MemoizedCutRod(int price, int lenght) {
  
          int[] r = new int[lenght + 1];
          for (int i = 1; i &lt;= lenght; i++) {
              r[i] = 0;
          }
          return MemoizedCutRodAux(price, lenght, r);
      }
  
      public static int MemoizedCutRodAux(int price, int lenght, int[] r) {
  
          int[] priceTable = new int[11];
          priceTable[1] = 1;
          priceTable[2] = 5;
          priceTable[3] = 8;
          priceTable[4] = 9;
          priceTable[5] = 10;
          priceTable[6] = 17;
          priceTable[7] = 17;
          priceTable[8] = 20;
          priceTable[9] = 24;
          priceTable[10] = 30;
  
          if (r[lenght] &gt;= 0) {
              return r[lenght];
          }
  
          if (lenght == 0) {
              return 0;
          }
          int q = 0;
  
          for (int i = 1; i &lt;= lenght; i++) {
              q = max(q, priceTable[i] + MemoizedCutRodAux(price, lenght, r));
              r[lenght] = q;
          }
          return q;
      }
  </code></pre>
  
  <p>All outputs of this code are 0. But non memorized version of this code is working. What is the problem with it? Here is the working code:</p>
  
  <pre><code>public class Simple {
  
      //finds maximum of two given integers
      public static int max(int a, int b) {
          return (a &gt; b) ? a : b;
  
      }
  
      public static int cormenCutRod(int price, int lenght) {
  
          int[] priceTable = new int[11];
          priceTable[1] = 1;
          priceTable[2] = 5;
          priceTable[3] = 8;
          priceTable[4] = 9;
          priceTable[5] = 10;
          priceTable[6] = 17;
          priceTable[7] = 17;
          priceTable[8] = 20;
          priceTable[9] = 24;
          priceTable[10] = 30;
  
          if (lenght == 0) {
              return 0;
          }
          int q = 0;
          for (int i = 1; i &lt;= lenght; i++) {
              q = max(q, priceTable[i] + cormenCutRod(price, lenght - i));
          }
  
          return q;
      }
  </code></pre>