ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Checkout Facade

Hide stock checks and price totals behind one simple checkout call.

สิ่งที่คุณจะได้เรียนรู้

  • Hide several subsystems behind one call
  • Check stock before charging
  • Combine repeated cart lines per item

โจทย์

ดูฉบับแปล

The facade pattern gives a simple entry point to a complicated subsystem. A shop's checkout call hides two subsystems: the inventory and the price list.

Items are numbered 0 to n − 1. stock[i] is how many units of item i are available and prices[i] is its price. The cart is a list of [item, quantity] lines; the same item may appear on several lines.

checkout(stock, prices, cart) must:

  1. Check the inventory: if the total quantity of any item in the cart is greater than its stock, the order fails.
  2. Otherwise return the total price of the cart.

Implement checkout_facade(stock, prices, cart).

Input

stock, prices: n values each.

cart: [item, quantity] lines.

Output

Return the total price, or -1 if any item does not have enough stock.

เงื่อนไข

1 ≤ n ≤ 1,000

0 ≤ stock[i], prices[i] ≤ 100,000; 0 ≤ cart lines ≤ 1,000; 1 ≤ quantity ≤ 1,000

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
cart = [
    [0, 2],
    [2, 4]
]
stock = [5, 2, 10]
prices = [3, 20, 1]

ผลลัพธ์ที่คาดหวัง:
expected = 10
อินพุต:
std::vector<std::vector<long long>> cart = {
    {0, 2},
    {2, 4}
};
std::vector<long long> stock = {5, 2, 10};
std::vector<long long> prices = {3, 20, 1};

ผลลัพธ์ที่คาดหวัง:
long long expected = 10;
อินพุต:
long[][] cart = new long[][] {
    new long[] {0, 2},
    new long[] {2, 4}
};
long[] stock = new long[] {5, 2, 10};
long[] prices = new long[] {3, 20, 1};

ผลลัพธ์ที่คาดหวัง:
long expected = 10;

คำอธิบาย

Both items are in stock. 2 × 3 + 4 × 1 = 10.

ตัวอย่างที่ 2
อินพุต:
cart = [
    [1, 1],
    [1, 2]
]
stock = [5, 2]
prices = [3, 20]

ผลลัพธ์ที่คาดหวัง:
expected = -1
อินพุต:
std::vector<std::vector<long long>> cart = {
    {1, 1},
    {1, 2}
};
std::vector<long long> stock = {5, 2};
std::vector<long long> prices = {3, 20};

ผลลัพธ์ที่คาดหวัง:
long long expected = -1;
อินพุต:
long[][] cart = new long[][] {
    new long[] {1, 1},
    new long[] {1, 2}
};
long[] stock = new long[] {5, 2};
long[] prices = new long[] {3, 20};

ผลลัพธ์ที่คาดหวัง:
long expected = -1;

คำอธิบาย

Item 1 appears twice for a total of 3 units, but only 2 are in stock, so the order fails: -1.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Add up the quantity of each item over all cart lines first.

คำใบ้ 2

Compare those totals with the stock before computing any price.

คำใบ้ 3

If any item is short, return -1 straight away.

ความซับซ้อนที่คาดหวัง

O(n + cart lines) time, O(n) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก