title: Knapsack without repetition
body: <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;algorithm&gt;
  using std::vector;
  
  int o_w(int W, const vector&lt;int&gt; &amp;w) {
    vector&lt;int&gt; c(W+1);
    for (size_t i = 0; i &lt; w.size(); ++i) {
        for(int j = W; j - w[i] &gt;= 0; --j) {
              c[j] = std::max(c[j], c[j - w[i]] + w[i]);
        }
    }
    return c[W];
  }
  
  int opti_w(int W,const std::vector&lt;int&gt; &amp;w,int n){
      std::vector&lt;std::vector&lt;int&gt;&gt; value(n+1,vector&lt;int&gt;(W+1,0));
      for(int i=0;i&lt;=n;i++){
          for(int j=0;j&lt;=W;j++){
              std::cout&lt;&lt;value[i][j]&lt;&lt;&quot; &quot;;
          }
          std::cout&lt;&lt;&quot;\n&quot;;
      }
  
      for(int i=1;i&lt;=n;i++){
        for(int j=1;j&lt;=W;j++){
         //value[j][i]=std::max(value[j][i-1],value[j-w[i]][i-1]+w[i]);
        std::cout&lt;&lt;&quot;i:&quot;&lt;&lt;i&lt;&lt;&quot; j:&quot;&lt;&lt;j&lt;&lt;&quot;\n&quot;;
        std::cout&lt;&lt;&quot;value[i][j]:&quot;&lt;&lt;value[i][j]&lt;&lt;&quot;\n&quot;;
        std::cout&lt;&lt;&quot;value[i-1][j]:&quot;&lt;&lt;value[i-1][j]&lt;&lt;&quot;\n&quot;;
        std::cout&lt;&lt;&quot;w[i-1]:&quot;&lt;&lt;w[i-1]&lt;&lt;&quot;\n&quot;;
        std::cout&lt;&lt;&quot;value[i-1][j-w[i-1]]:&quot;&lt;&lt;value[i-1][j-w[i-1]]&lt;&lt;&quot;\n&quot;;
        std::cout&lt;&lt;&quot;value[i-1][j-w[i-1]]+w[i-1]:&quot;&lt;&lt;value[i-1][j-w[i-1]]+w[i-1]&lt;&lt;&quot;\n&quot;;
        value[i][j]=std::max(value[i-1][j],  value[i-1][j-w[i-1]] +w[i-1]  );
        }
      }
      
       for(int i=0;i&lt;=n;i++){
          for(int j=0;j&lt;=W;j++){
              std::cout&lt;&lt;value[i][j]&lt;&lt;&quot; &quot;;
          }
          std::cout&lt;&lt;&quot;\n&quot;;
      }
  
      return value[n][W];
     // return value[W][n];
  }
  
  int main() {
    int n, W;
    std::cin &gt;&gt; W &gt;&gt; n;
    vector&lt;int&gt; w(n);
    for (int i = 0; i &lt; n; i++) {
      std::cin &gt;&gt; w[i];
    }
    std::cout&lt;&lt;opti_w(W, w, n);
    //std::cout &lt;&lt; o_w(W, w) &lt;&lt; '\n';
  }
  </code></pre>
  <p>In function opti_w I am somehow using the wrong formula or getting something wrong due to which I am unable to get correct values because sometime j-[w-1] becomes negative hence unwanted elements gets accessed.</p>
  <p>Function o_w is correct and can be used to verify answers.</p>
  <p>How can I approach to resolve the issue and whats incorrect in the solution.</p>