DreamGrid's Luxury Shopping
Practice
3 (4 votes)
Greedy algorithm
Algorithms
Arrays
Greedy algorithms
Basics of greedy algorithms
Problem
87% Success 2569 Attempts 30 Points 1s Time Limit 256MB Memory 1024 KB Max Code

DreamGrid recently went on a shopping spree for luxury items at an exclusive boutique. In this boutique, there were \(n\) distinct items to choose from. DreamGrid, known for his ample wealth, employed an interesting shopping strategy:

  • He meticulously inspected all \(n\) items in the store, starting from the \(1^{\text{st}}\) item and ending with the \(n^{\text{th}}\) item.
  • Whenever he checked an item, he only made a purchase if he had enough funds to cover its price. If his available funds were sufficient, he bought the item and subtracted its cost from his total wealth.
  • If, at any point, his remaining funds were insufficient to buy the item being considered, he would simply skip that particular item.

Your task is to determine the maximum possible amount of wealth DreamGrid had at the beginning such that he can acquire some of these luxury items. You are provided with the prices of the \(n\) items and the total number of items DreamGrid ultimately purchased (indicated as \(m\)).

Your objective is to find out DreamGrid's maximum wealth that DreamGrid has before this extravagant shopping spree such that he can purchase \(m\) luxury items, which will be a non-negative whole number.

Input format

  • The first line consists of two integers \(n\) and \(m\), separated by a space. Here, \(n\)denotes the total number of luxury items available in the boutique, and \(m\) represents the number of items DreamGrid eventually purchased.
  • The next \(n\) lines each contains one integer \(\text{price}_i\) indicates the price of the \(i^{\text{th}}\) luxury item.

Output format

Print the maximum amount of money DreamGrid needs to purchase \(m\) items in a new line.

Constraints

\(1 \leq n \leq 10^5 \\ 0 \leq m \lt n\\ 1 \leq \text{price}_i \leq 10^9\)

 

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
2 votes
Tags:
AlgorithmsGreedy AlgorithmsBasics of Greedy AlgorithmsGreedy algorithm
Points:30
3 votes
Tags:
Greedy algorithmGreedy AlgorithmsAlgorithmsBasics of Greedy AlgorithmsDatastructures
Points:30
1 votes
Tags:
AlgorithmsBasics of Greedy AlgorithmsC++Greedy Algorithms