Leetcode 1860: Incremental Memory Leak

grid47
grid47
Exploring patterns and algorithms
May 5, 2024 5 min read

You are given two memory sticks with certain amounts of available memory. A program runs and allocates increasing amounts of memory to the stick with more available memory. If neither stick has enough memory to allocate the required amount, the program crashes. Determine when the program crashes and the remaining memory on each stick.
Problem
Approach
Steps
Complexity
Input: The input consists of two integers, memory1 and memory2, representing the available memory on the two sticks.
Example: memory1 = 5, memory2 = 6
Constraints:
• 0 <= memory1, memory2 <= 2^31 - 1
Output: The output is an array with three elements: the crash time (the second at which the program crashes), the remaining memory on the first stick, and the remaining memory on the second stick.
Example: [4, 0, 2]
Constraints:
• The program crashes when one of the memory sticks cannot allocate the required memory.
Goal: Simulate the memory allocation process until the program crashes. At each second, allocate memory to the stick with more available memory, or to the first stick if both sticks have the same available memory. Stop when neither stick has enough memory to allocate.
Steps:
• At each second, compare the available memory on both sticks.
• Allocate i bits to the stick with more available memory.
• If both sticks have the same available memory, allocate to the first stick.
• If neither stick has enough memory to allocate i bits, return the crash time and the remaining memory on both sticks.
Goal: The input consists of two integers representing the available memory, and the output should indicate when the program crashes.
Steps:
• 0 <= memory1, memory2 <= 2^31 - 1
• The program will crash within a reasonable number of seconds, given the constraints.
Assumptions:
• Both memory sticks have a non-negative amount of memory.
Input: Input: memory1 = 5, memory2 = 6
Explanation: The memory is allocated as follows: At the 1st second, 1 bit is allocated to stick 2 (memory2 = 5). At the 2nd second, 2 bits are allocated to stick 2 (memory2 = 3). At the 3rd second, 3 bits are allocated to stick 1 (memory1 = 2). At the 4th second, 4 bits are allocated to stick 2 (memory2 = -1). The program crashes here.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus