Incremental Memory Leak LeetCode Solution - The Coding Shala

Home >> LeetCode >> Incremental Memory Leak

 In this post, we will learn how to solve LeetCode's Incremental Memory Leak Problem and will implement its solution in Java.

Incremental Memory Leak Problem

You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.

Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.

Example 1:
Input: memory1 = 2, memory2 = 2
Output: [3,1,0]
Explanation: The memory is allocated as follows:
- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.
- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.
- In the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.

Practice this problem on LeetCode.

LeetCode - Incremental Memory Leak Java Solution

Approach 1

Brute Force.

Java Program: 

class Solution {
    public int[] memLeak(int memory1, int memory2) {
        int time = 1;
        int mem = 1;
        while(mem <= memory1 || mem <= memory2) {
            if(memory1 >= memory2) {
                if(memory1 >= mem) {
                    memory1 -= mem;
                } else {
                    // crash
                    break;
                }
            } else {
                if(memory2 >= mem) {
                    memory2 -= mem;
                } else {
                    // crash
                    break;
                }
            }
            mem++;
            time++;
        }
        int[] res = {time, memory1, memory2};
        return res;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

Maximum Population Year LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala