💥 Beats 100% on runtime and memory [EXPLAINED]
Intuition\nThe problem revolves around managing energy effectively while completing tasks. Each task requires a minimum energy to start and consumes a certain a
# Intuition\nThe problem revolves around managing energy effectively while completing tasks. Each task requires a minimum energy to start and consumes a certain amount of energy. If your current energy is insufficient for a task, you need to ensure you start with enough energy to complete all tasks without running out.\n\n# Approach\nSort the tasks based on the difference between minimum and actual energy needed, then iterate through them, adjusting the initial energy required if your current energy falls below the minimum needed for each task.\n\n# Complexity\n- Time complexity:\nO(n log n) due to sorting the tasks.\n\n- Space complexity:\nO(n) because sorting can use additional space for temporary storage.\n\n# Code\n```typescript []\n/**\n * @param {number[][]} tasks - A 2D array where each sub-array contains the actual energy spent and the minimum energy required for each task.\n * @return {number} - The minimum initial energy required to finish all tasks.\n */\nfunction minimumEffort(tasks: number[][]): number {\n    // Sort tasks primarily by the difference (minimum - actual) in descending order\n    tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]));\n\n    let minimumEnergy = 0; // Minimum energy needed to start\n    let currentEnergy = 0; // Current energy level after completing tasks\n\n    for (const [actual, minimum] of tasks) {\n        // If current energy is insufficient for the next task\n        if (currentEnergy < minimum) {\n            // Calculate how much more energy is needed\n            const energyNeeded = minimum - currentEnergy;\n            minimumEnergy += energyNeeded; // Increase the minimum energy required\n            currentEnergy += energyNeeded; // Simulate starting with that much energy\n        }\n        // After the task, decrease the current energy\n        currentEnergy -= actual; \n    }\n\n    return minimumEnergy; // Return the total minimum energy needed\n}\n\n// Example test cases\nconsole.log(minimumEffort([[1, 2], [2, 4], [4, 8]]));  // Expected output: 8\nconsole.log(minimumEffort([[1, 3], [2, 4], [10, 11], [10, 12], [8, 9]]));  // Expected output: 32\nconsole.log(minimumEffort([[1, 7], [2, 8], [3, 9], [4, 10], [5, 11], [6, 12]]));  // Expected output: 27\n\n```
['TypeScript']