Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This seems like a good candidate for dynamic programming:</p> <pre><code>//int[,] discountTable = new int[NumItems][NumCoupons+1] // bestDiscount[i][c] means the best discount if you can spend c coupons on items 0..i int[,] bestDiscount = new int[NumItems][NumCoupons+1]; // the best discount for a set of one item is just use the all of the coupons on it for (int c=1; c&lt;=MaxNumCoupons; c++) bestDiscount[0, c] = discountTable[0, c]; // the best discount for [i, c] is spending x coupons on items 0..i-1, and c-x coupons on item i for (int i=1; i&lt;NumItems; i++) for (int c=1; c&lt;=NumCoupons; c++) for (int x=0; x&lt;c; x++) bestDiscount[i, c] = Math.Max(bestDiscount[i, c], bestDiscount[i-1, x] + discountTable[i, c-x]); </code></pre> <p>At the end of this, the best discount will be the highest value of bestDiscount[NumItems][x]. To rebuild the tree, follow the graph backwards:</p> <p>edit to add algorithm:</p> <pre><code>//int couponsLeft; for (int i=NumItems-1; i&gt;=0; i++) { int bestSpend = 0; for (int c=1; c&lt;=couponsLeft; c++) if (bestDiscount[i, couponsLeft - c] &gt; bestDiscount[i, couponsLeft - bestSpend]) bestSpend = c; if (i == NumItems - 1) Console.WriteLine("Had {0} coupons left over", bestSpend); else Console.WriteLine("Spent {0} coupons on item {1}", bestSpend, i+1); couponsLeft -= bestSpend; } Console.WriteLine("Spent {0} coupons on item 0", couponsLeft); </code></pre> <p>Storing the graph in your data structure is also a good way, but that was the way I had thought of.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload