LeetCode 2141: Maximum Running Time of N Computers Solution

Master LeetCode problem 2141 (Maximum Running Time of N Computers), a hard 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.

2141. Maximum Running Time of N Computers

Problem Explanation

Explanation:

To maximize the running time of all n computers simultaneously, we need to carefully manage the batteries. We can achieve this by inserting batteries with the longest remaining runtime into the computers and swapping batteries when needed. The key idea is to always have the maximum possible total running time across all computers.

  1. Sort the batteries in descending order.
  2. Initialize a priority queue (max heap) to store the remaining battery times.
  3. Iterate through the batteries, inserting them into computers and updating the total running time.
  4. If a battery is drained, remove it from the queue and insert a new battery with the longest remaining time.
  5. Continue this process until all computers stop running.

Time Complexity: O(n log n) where n is the number of batteries. Space Complexity: O(n) for the priority queue.

:

Solution Code

import java.util.Arrays;
import java.util.PriorityQueue;

class Solution {
    public int maxRunningTime(int n, int[] batteries) {
        Arrays.sort(batteries);
        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
        int totalTime = 0;
        
        for (int battery : batteries) {
            pq.offer(battery);
            totalTime += battery;
            if (pq.size() > n) {
                totalTime -= pq.poll();
            }
        }
        
        return totalTime;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2141 (Maximum Running Time of N Computers)?

This page provides optimized solutions for LeetCode problem 2141 (Maximum Running Time of N Computers) 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 2141 (Maximum Running Time of N Computers)?

The time complexity for LeetCode 2141 (Maximum Running Time of N Computers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2141 on DevExCode?

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

Back to LeetCode Solutions