समस्या
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:
- Check the inventory: if the total quantity of any item in the cart is greater than its stock, the order fails.
- Otherwise return the total price of the cart.
Implement checkout_facade(stock, prices, cart).
इनपुट
stock, prices: n values each.
cart: [item, quantity] lines.
आउटपुट
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 ≤ कार्ट की लाइनें ≤ 1,000; 1 ≤ quantity ≤ 1,000
उदाहरण
इनपुट:
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;
व्याख्या
दोनों items stock में हैं। 2 × 3 + 4 × 1 = 10.
इनपुट:
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 दो बार आता है, कुल 3 units के लिए, लेकिन stock में केवल 2 हैं, इसलिए order fail हो जाता है: -1.
कैसे हल करें
पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।
संकेत 1
पहले सभी कार्ट लाइनों में हर आइटम की मात्रा जोड़ें।
संकेत 2
कोई भी कीमत निकालने से पहले उन जोड़ों की तुलना स्टॉक से करें।
संकेत 3
अगर कोई आइटम कम है, तो तुरंत -1 लौटाएँ।
अपेक्षित जटिलता
समय O(n + कार्ट लाइनें), अतिरिक्त स्थान O(n)
संदर्भ
यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।