-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a14d27f
commit 36fd0a1
Showing
3 changed files
with
42 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { minEatingSpeed } from './minEatingSpeed'; | ||
|
||
describe('875. Koko Eating Bananas', () => { | ||
test('minEatingSpeed', () => { | ||
expect(minEatingSpeed([3, 6, 7, 11], 8)).toBe(4); | ||
expect(minEatingSpeed([30, 11, 23, 4, 20], 5)).toBe(30); | ||
expect(minEatingSpeed([30, 11, 23, 4, 20], 6)).toBe(23); | ||
}); | ||
}); |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
type MinEatingSpeed = (piles: number[], h: number) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const minEatingSpeed: MinEatingSpeed = (piles, h) => { | ||
let left = 1; | ||
let right = Math.max(...piles); | ||
|
||
const canEatAll = (k: number): boolean => { | ||
let hours = 0; | ||
|
||
for (const pile of piles) { | ||
hours += Math.ceil(pile / k); | ||
} | ||
|
||
return hours <= h; | ||
}; | ||
|
||
while (left < right) { | ||
const mid = Math.floor((left + right) / 2); | ||
|
||
if (canEatAll(mid)) { | ||
right = mid; // Try smaller k | ||
} else { | ||
left = mid + 1; // Try larger k | ||
} | ||
} | ||
|
||
return left; | ||
}; |