모든 챌린지
쉬움 0명 해결 정답률 0%

Price Decorators

Wrap a base price in discount, tax, shipping and coupon decorators applied in order.

배우게 될 내용

  • Stack behaviours in layers around a value
  • Apply percentages in the right order
  • Clamp a value so it never goes below zero

문제

번역본 보기

The decorator pattern adds behaviour by wrapping an object in layers. Each layer here changes the price of the layer inside it.

Start from base_price and apply the decorators in order:

  • discount p: reduce the price by p percent.
  • tax p: increase the price by p percent.
  • shipping a: add a fixed amount a.
  • coupon a: subtract a, but never go below 0.

Implement price_decorators(base_price, decorators).

Input

base_price: The starting price.

decorators: The layers, in the order they wrap the price. Amounts may have decimals.

Output

Return the final price. Answers within 1e-6 are accepted.

제약 조건

0 ≤ base_price ≤ 1,000,000

0 ≤ number of decorators ≤ 100; 0 ≤ p ≤ 100, 0 ≤ a ≤ 100,000

예시

예시 1
입력:
base_price = 100
decorators = ["discount 10", "tax 8", "shipping 5"]

예상 출력:
expected = 102.2
입력:
long long base_price = 100;
std::vector<std::string> decorators = {"discount 10", "tax 8", "shipping 5"};

예상 출력:
double expected = 102.2;
입력:
long base_price = 100;
string[] decorators = new string[] {"discount 10", "tax 8", "shipping 5"};

예상 출력:
double expected = 102.2;

설명

100 − 10% = 90, plus 8% tax = 97.2, plus 5 shipping = 102.2.

예시 2
입력:
base_price = 20
decorators = ["coupon 25", "shipping 4"]

예상 출력:
expected = 4.0
입력:
long long base_price = 20;
std::vector<std::string> decorators = {"coupon 25", "shipping 4"};

예상 출력:
double expected = 4.0;
입력:
long base_price = 20;
string[] decorators = new string[] {"coupon 25", "shipping 4"};

예상 출력:
double expected = 4.0;

설명

The coupon would take the price below zero, so it stops at 0; shipping then makes it 4.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Apply the layers strictly in the given order.

힌트 2

Percentages are taken from the current price, not the base price.

힌트 3

A coupon can never push the price below 0.

예상 복잡도

O(number of decorators) time, O(1) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.