경쟁 프로그래밍쉬움

분수 배낭

'Fractional Knapsack' 문제에 대한 자세한 가이드 및 Python 구현입니다.

문제 설명

쉬움

배낭 용량 W과 튜플 목록 items을 사용하는 함수 fractional_knapsack(W, items)를 작성하세요. 여기서 각 튜플은 (value, weight)입니다. 아이템을 부수거나 나눌 수 있도록 배낭에서 얻을 수 있는 최대 총 가치를 구합니다. 출력을 소수점 이하 2자리로 반올림합니다.

제약
  • 1 <= len(items) <= 1000
  • 1 <= W <= 10^5
  • 1 <= value, weight <= 10^4

Example 1
Input
fractional_knapsack(50, [(60, 10), (100, 20), (120, 30)])
Output
240.0
Explanation

Take the first and second item fully, and 2/3 of the third item. Total value: 60 + 100 + 120 * (20/30) = 240.0.

Example 2
Input
fractional_knapsack(15, [(24, 10), (18, 10), (15, 10)])
Output
33.0
Explanation

Take the first item fully, and 1/2 of the second item. Total value: 24 + 18 * 0.5 = 33.0.

Need a Hint?
세트나 힙과 같은 Greedy 관련 데이터 구조를 사용하는 것을 고려해보세요.
Edge Cases to Watch
  • 빈 입력 구조
  • 단일 요소 입력
  • 큰 수치 범위

해결할 준비가 되셨나요?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

편집기에서 열기
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

권장 Python 리소스

관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.