How do I lessen the memory usage of my solution to LeetCode 495: Teemo Attacking
Disclaimer: Not a Code Reviewer

Just tested your code, it has a 1ms runtime with 99.97% faster than other solutions.


Don't pay too much attention to these runtime/memory data provided by LeetCode especially when:

it comes to memory; or
test cases are too limited (such as Teemo) because their benchmarkings are not so accurate.


Maybe instead we'd format the code, just a bit making things based on Java's conventions:


public class Solution {
    public static final int findPoisonedDuration(
        final int[] timeSeries,
        final int duration
    ) {

        int i = 0;
        int oldGoalpost = 0;
        int newGoalpost = 0;
        int diff = 0;
        int numberOfSeconds = duration;

        if (timeSeries.length &gt; 0) {
            oldGoalpost = timeSeries[0] + duration - 1;

        } else {
            numberOfSeconds = 0;
        }

        if (timeSeries.length &gt; 0)
            for (i = 1; i &lt; timeSeries.length; i++) {
                newGoalpost =  timeSeries[i] + duration - 1;

                diff = (newGoalpost - oldGoalpost) &gt; duration ? duration : ((newGoalpost - oldGoalpost));


                numberOfSeconds = numberOfSeconds + diff;
                oldGoalpost = newGoalpost;

            }

        return numberOfSeconds;

    }
}



Your solution has an order of N runtime with constant memory O(1).
Algorithmically speaking, which is a key point on solving LeetCode questions, I don't think much can be done to make it any further efficient, I might be wrong though.

public class Solution {
    public static final int findPoisonedDuration(
        final int[] series,
        final int duration
    ) {
        if (series.length == 0 || duration == 0) {
            return 0;
        }

        int totalTime = duration;

        for (int i = 1; i &lt; series.length; i++) {
            totalTime += Math.min(series[i] - series[i - 1], duration);
        }

        return totalTime;
    }
}