Skip to content

Instantly share code, notes, and snippets.

@skipzero
Created March 17, 2023 15:06
Show Gist options
  • Save skipzero/a9427870eb493740e9bcdd4762c88582 to your computer and use it in GitHub Desktop.
Save skipzero/a9427870eb493740e9bcdd4762c88582 to your computer and use it in GitHub Desktop.

Revisions

  1. skipzero created this gist Mar 17, 2023.
    34 changes: 34 additions & 0 deletions Sticks.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    /**
    * in tackling this problem, I simply sorted the array, putting the larger sizes first.
    * Once I had the array sorted, I started with the biggest size and worked my way through it.
    * basically just sor tthe array and subtract from the length needed (k)
    *
    * I'm not sure if this passes the Big O notation requirement, I assume so with it being
    * super simple and only having one for loop. That should help keep complexity down.
    *
    *
    */

    const getMinSticks = (sticks, k) => {
    let stickCount = 0;
    let remaining = k;
    sticks.sort((a,b) => {
    return a > b ? -1 : 0
    })


    for (let i = 0; i < sticks.length; i++) {
    const length = sticks[i];
    const needed = Math.floor(remaining / length);
    let used = Math.min(needed, sticks[i])
    stickCount += used;
    remaining -= used * length;
    }
    console.log('returned', remaining === 0 ? stickCount : -1)
    return remaining === 0 ? stickCount : -1
    }

    const sticks = [1, 2, 3, 4];
    const k = 8;

    getMinSticks(sticks, 25)