AMAZON Coding Question – Solved

9 Live
Amazon Kindle has several e-books that customers can purchase directly. There are n books ordered sequentially numbered 1, 2, ..., n, where the ith book has a cost of cost[i]. A customer wants to purchase all the books, and Kindle offers the customer a unique discount to minimize their total cost. The discount is described as follows: 1. Let the leftmost book remaining in the sequence be book i. The customer can choose to buy the leftmost book individually for cost[i]. This book is then removed from the sequence. 2. Let the rightmost book remaining in the sequence be book j. The customer can choose to buy the rightmost book individually for cost[j]. This book is then removed from the sequence. 3. The customer can also choose to pay the amount `pairCost` for both the leftmost and rightmost books together. In this case, both books are removed. This option can be used at most k times. Given the cost of books `cost`, the cost to purchase the leftmost and rightmost books together `pairCost`, and the maximum number of times the pairCost option can be applied `k`, find the minimum cost in which the customer can purchase all the books. Example: n = 3 cost = [1, 2, 3] pairCost = 2 k = 1 All books are purchased optimally as follows: - Buy book 1 and 3 using pairCost = 2 - Buy book 2 individually = 2 Total cost = 4 Constraints: · 1 ≤ n ≤ 10⁵ · 1 ≤ pairCost ≤ 10⁹ · 1 ≤ k ≤ n · 1 ≤ cost[i] ≤ 10⁹ · The cost array may not be sorted in any particular order. Input Format for Custom Testing: Sample Input: 5 9 11 13 15 17 6 2 Function: - cost[] size n = 5 - cost = [9, 11, 13, 15, 17] - pairCost = 6 - k = 2 Sample Output: 21 Explanation: - Purchase the leftmost book individually: cost[0] = 9 - Purchase leftmost and rightmost books using pairCost = 6 (books 11 and 17) - Purchase remaining books (13 and 15) individually or with pairCost depending on what's optimal Total minimum cost = 21

Asked in: AMAZON

Image of the Question

Question Image Question Image Question Image

All Testcases Passed ✔



Passcode Image

Solution


from functools import lru_cache
from sys import setrecursionlimit
setrecursionlimit(10**6)
def findMinPrice(cost, pairCost, k):
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
This problem revolves around a sequential purchasing decision with three possible operations, and a limited number of times you can apply a special combined discount. The main goal is to minimize total cost of buying all books, either individually or as pairs from the ends, respecting the constraint on how many pairs you can buy using the discounted pair cost.

To approach this problem, begin by carefully analyzing the problem structure and constraints:

1. **Problem Restatement:**
You have a sequence of books from 1 to n with given individual costs. You can either:
- Buy the leftmost book alone at its cost.
- Buy the rightmost book alone at its cost.
- Buy both the leftmost and rightmost books together at a fixed pairCost, but you can only do this at most k times.

Your goal is to remove all books by repeatedly applying these operations, minimizing the total spent.

2. **Important Observations:**
- The sequence shrinks from the outside inward as books are bought and removed from either end.
- The pairing option removes two books simultaneously but is limited in use.
- When pairing, you pay a fixed cost regardless of the actual individual costs of the two books.
- Buying individually may cost more or less than pairCost depending on book costs.
- The cost array is not sorted, so you cannot rely on simple monotonic properties.

3. **Constraints and Their Effects:**
- Since n can be as large as 10^5, an O(n^2) approach that tries every possibility naively is not feasible.
- You need an efficient way to evaluate buying books from both ends, considering the pair cost limit.
- This suggests dynamic programming or two-pointer techniques to explore subproblems efficiently.

4. **Core Problem Decomposition:**
Think of the sequence as having two pointers: one at the start (left) and one at the end (right). At any point:
- You can buy the left book and move left pointer inward (left += 1).
- Or buy the right book and move right pointer inward (right -= 1).
- Or buy both ends together if you have remaining pair purchases (k > 0), moving both pointers inward (left += 1, right -= 1) and using up one pair purchase.

The problem reduces to choosing a sequence of these actions that leads to minimum total cost.

5. **What to Store in Subproblems:**
A natural way to represent the problem is through states defined by:
- The current indices of the left and right pointers (defining the remaining books).
- How many pairs have been used so far (or how many are left).

From this, you can define a function `dp(left, right, pairs_used)` which returns the minimum cost to buy all books between indices `left` and `right` with `pairs_used` pairs used.

6. **Transitions:**
From `dp(left, right, pairs_used)`, you can consider:
- Buying left book individually: cost = cost[left] + dp(left+1, right, pairs_used)
- Buying right book individually: cost = cost[right] + dp(left, right-1, pairs_used)
- Buying both left and right using a pair (if pairs_used < k): cost = pairCost + dp(left+1, right-1, pairs_used+1)

You choose the minimum among these options.

7. **Base Cases:**
- If left > right, no books remain, cost is zero.
- If left == right, only one book remains, so you buy it individually.

8. **Optimization Thoughts:**
- The dp state space is O(n^2 * k) which can be too large for n=10^5.
- But since pair usage `k` can be at most n/2 (because each pair removes 2 books), you need more efficient methods.

9. **Potential Optimization Strategies:**
- Use **prefix sums** to quickly calculate costs of buying segments individually without pairs.
- Consider the number of pairs used as a parameter and figure out the minimal cost for each number of pairs used.
- The problem can be reduced to trying all possible numbers of pairs used from 0 to k, then compute the minimal cost for each scenario.

10. **Two Pointer + Prefix Sum Approach:**
You can consider choosing how many pairs to use `p` (from 0 to k). Each pair removes two books, so using `p` pairs removes `2p` books. The remaining books must be bought individually from the center.

For a fixed `p`, the minimum cost is:
- `p * pairCost` (cost of all pairs) + cost of the remaining books bought individually.

Since pairs remove books from both ends, the remaining books are a contiguous subarray in the middle. For each possible `p`, find the minimal sum of the middle subarray (the books not included in pairs).

11. **Finding the minimal sum of middle segment:**
For a fixed `p`, pairs remove `p` books from left and `p` books from right.
The middle subarray is from index `p` to `n - p - 1`.
The cost of buying these individually is sum(cost[p] to cost[n-p-1]).
You want to minimize this sum by adjusting `p`.

12. **Combine the above:**
Precompute prefix sums to quickly get the sum of any segment.
For each `p` in `[0, k]`, calculate total cost = `p * pairCost + sum of middle segment`.
The answer is the minimum over all these values.

13. **Handling edge cases:**
- When `p` is 0, no pairs are used; buy all individually.
- When `p` is maximum, all books are bought in pairs (if n is even and pairs allowed).
- If `n` is odd, the middle single book must be bought individually.

14. **Summary:**
This approach leverages the problem’s symmetry and constraints, turning an initially complex sequential decision into a straightforward minimization over possible pair counts.
By trying all feasible counts of pairs used, and buying the rest individually from the center segment, you find the minimum total cost efficiently.
The key insight is realizing that using pairs removes equal numbers of books from both ends and leaves a contiguous block in the middle to be purchased individually, which you can compute quickly with prefix sums.

In conclusion, the main direction to think in is:
- Understand the problem as removing books from both ends with optional pair discounts.
- Realize the problem can be parameterized by how many pairs you use.
- Use prefix sums to efficiently calculate cost for any middle segment.
- Try all feasible pair counts to find minimal cost.

This approach is optimal, handles large constraints, and captures the essential decision points clearly.
```


Related Questions