Minimum Cost to Buy Oranges

You are given a bag of size 'W' kg and provided with the costs of packets with different weights of oranges as a list/array with the name 'cost'. Every i-th position in the cost denotes the price of 'i+1' kg packet of oranges.

If at any point in time the i-th cost is -1, it means that 'i+1' kg packet of orange is unavailable.

You are required to find the minimum total cost to buy exactly 'W' kg oranges and if it's not possible to buy precisely W kg oranges then print -1. There is an infinite supply of all available packet types.

Note :
Array index 'i' denotes the cost of (i+1)kg packet. 
Example: cost[0] is the cost of a 1kg packet of oranges.
Input Format :
The first line of each test case contains two single space-separated integers 'N' and 'W' where 'N' denotes the size of the array/list(cost), and 'W' is the bag's size.

The second line of each test case contains 'N' single space-separated integers denoting the values of the cost.
Output Format :
Print the minimum cost to buy exactly W kg oranges. If it's impossible, print "-1".
Note :
You are not required to print anything, it has already been taken care of. Just implement the function.
Constraints :
1 <= N <= 1000
1 <= W <= 1000
-1 <= cost[i] <= 1000000

Time Limit: 1sec
CodingNinjas
author
2y
Recursive Approach

Write a recursive function minCostToBuyOrangesHelper(idx, requiredWeight, n) to return the Minimum cost to buy exactly requiredWeight Kg oranges with (idx+1) Kg to N kg packets.

  1. Our m...read more
CodingNinjas
author
2y
Memoization

We will write a recursive function minCostToBuyOrangesHelper(idx, requiredWeight, n) to return the Minimum cost to buy exactly requiredWeight Kg oranges with (idx+1) Kg to N kg packets. The...read more

CodingNinjas
author
2y
Iterative DP

We will write an iterative DP where minCost[i][j] denotes the minimum cost of buying exactly 'j' kg Oranges with 1 to 'i’ kg packets of oranges.

  1. The base cases are:
  2. We will be Initializing 0...read more
CodingNinjas
author
2y
Space Optimised Iterative DP

We will write an iterative DP using 1D DP array where minCost[i] denotes Minimum cost of buying exactly 'i' kg Oranges with all the packets of oranges.

  1. The base cases are:
    1. In...read more
Add answer anonymously...
Wipro Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter