703149. Sid and his prime money

Hard

Sid and his Prime Money

Summary

Sid has a stash of money, and he wants to allocate it wisely. He knows that prime numbers are special, so he decides to invest in them. The goal is to maximize the sum of the prime numbers Sid can buy with his available money. Given an array of coin denominations and the total amount of money Sid has, find out how many prime numbers he can buy and what their sum will be.

Detailed Explanation

To solve this problem, we'll use a combination of mathematical and algorithmic techniques. First, let's create a function to check if a given number is prime or not. Then, we'll sort the coin denominations in descending order and iterate through them to find the maximum number of prime numbers that can be bought.

Here's a step-by-step breakdown:

  1. Initialize an empty array primes to store the prime numbers.
  2. Iterate over the range from 2 to the total amount of money (inclusive).
  3. For each number, check if it's prime using the function created in step 1.
  4. If the number is prime, add it to the primes array.
  5. Sort the primes array in descending order.
  6. Initialize a variable sum to store the sum of the prime numbers bought.
  7. Iterate through the sorted primes array and for each prime number:
    • Check if the total amount of money is sufficient to buy the prime number (i.e., the prime number is less than or equal to the remaining amount).
    • If it's sufficient, subtract the prime number from the total amount and add it to the sum.
  8. Return the maximum sum of prime numbers that can be bought.

Time complexity: O(n log n) due to sorting the primes array. Space complexity: O(n) for storing the prime numbers in the primes array.

Optimized Solutions

Java

View on GeeksforGeeks
public class SidAndPrimeMoney {
    public static int maxPrimeSum(int[] coins, int totalAmount) {
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= totalAmount; i++) {
            if (isPrime(i)) {
                primes.add(i);
            }
        }
        Collections.sort(primes, Comparator.reverseOrder());
        int sum = 0;
        for (int prime : primes) {
            while (totalAmount >= prime && totalAmount - prime >= 0) {
                totalAmount -= prime;
                sum += prime;
            }
        }
        return sum;
    }

    private static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.