Created
          March 17, 2023 15:06 
        
      - 
      
- 
        Save skipzero/a9427870eb493740e9bcdd4762c88582 to your computer and use it in GitHub Desktop. 
    a hackerrank/leetcode type problem for finding the amount of array items (sticks) it would take to get to a given sum (k)
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | /** | |
| * 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) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment