Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Minimum and Maximum Cost to buy N Candies
HARD
10 mins
11 upvotes
Arrays
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Arrays
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Minimum and Maximum Cost to buy N Candies

Contributed by
Mutiur Rehman khan
Hard
yellow-spark
0/120
Avg time to solve 10 mins
Success Rate 90 %
Share
11 upvotes

Problem Statement

Ram went to a specialty candy store in Ninjaland which has 'N' candies with different costs.

The Candy shop gives a special offer to its customers. A customer can buy a single candy from the store and get at most 'K' different candies for free. Now, Ram is interested in knowing the maximum and the minimum amount he needs to spend for buying all the candies available in the store.

Note: In both cases, Ram must utilize the offer i.e. if 'K' or more candies are available, he must take 'K' candies for every candy purchase. If less than K candies are available, he must take all candies for a candy purchase.

For Example :

For 'N' =  5 and 'K' = 2

Let the cost of different candies in the store be: [9 8 2 6 4]

For the minimum amount: 
Ram can buy a candy with cost 2 and take candies with costs 9 and 8 for free. 
Then, he can buy a candy with cost 4 and take candy with cost 7 for free. 
Thus, the minimum cost will be 6 i.e. 2 + 4. 

For the maximum amount: 
Ram can buy a candy with cost 9 and take candies with costs 2 and 6 for free. 
Then, he can buy candy at cost 8 and take candy at cost 4 for free. 
Thus, the minimum cost will be 17 i.e. 9 + 8.

Thus, Minimum = 6 and Maximum = 17.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
1
4 2
3 2 1 4
Sample Output 1 :
3 7
Explanation :
For the minimum amount: 
Ram can buy candy with cost 1 and take candies with costs 3 and 4 for free. 
Then, he can buy candy with cost 2.
Thus, the minimum cost will be 3 i.e. 1 + 2. 

For the maximum amount: 
Ram can buy candy with cost 4 and take candies with costs 1 and 2 for free. 
Then, he can buy candy with cost 3. 
Thus, the minimum cost will be 7 i.e. 4 + 3.
Sample Input 2:
2
5 2
9 8 2 6 4
3 0
1 5 4
Sample Output 2 :
6 17
10 10
Reset Code
Full screen
Auto
copy-code
Console