LeetCode 2979: Most Expensive Item That Can Not Be Bought Solution

Master LeetCode problem 2979 (Most Expensive Item That Can Not Be Bought), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2979. Most Expensive Item That Can Not Be Bought

Problem Explanation

Explanation

To solve this problem, we can use a greedy approach. We iterate through the given items and sort them based on their price in descending order. Then we iterate through the sorted items and check if we can buy the current item by subtracting its price from the total money we have. If we can buy the item, we update the total money left. If we reach an item that we cannot buy, we return the price of that item as the result.

Algorithm:

  1. Sort the items based on their price in descending order.
  2. Initialize a variable moneyLeft to store the total money we have.
  3. Iterate through the sorted items:
    • If we can buy the current item, update moneyLeft.
    • If we cannot buy the current item, return its price as the result.

Time Complexity

The time complexity of this approach is O(nlogn) where n is the number of items.

Space Complexity

The space complexity of this approach is O(1) as we are not using any extra space other than a few variables.

Solution Code

import java.util.Arrays;

class Solution {
    public int mostExpensiveItem(int[] items, int money) {
        Arrays.sort(items);
        int moneyLeft = money;
        for (int item : items) {
            if (item <= moneyLeft) {
                moneyLeft -= item;
            } else {
                return item;
            }
        }
        return -1; // If no item is found that cannot be bought
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2979 (Most Expensive Item That Can Not Be Bought)?

This page provides optimized solutions for LeetCode problem 2979 (Most Expensive Item That Can Not Be Bought) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2979 (Most Expensive Item That Can Not Be Bought)?

The time complexity for LeetCode 2979 (Most Expensive Item That Can Not Be Bought) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2979 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2979 in Java, C++, or Python.

Back to LeetCode Solutions