How to make changes in my code so that it can take the least memory possible.? This is a leetcode program , I have tested all the testcases and it has passed, I tried to reduce the memory usage, but by far now, I have not been able to understand.
I want to look into this so that I can understand the usage of memory spaces better. Any input would be helpful. Thank you very much. I will also post the link to the question, but since the logic is already clear to me, The only question is that is this a good solution or memory heavy?
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int i =0,old_goalpost=0,new_goalpost=0 ,diff=0;
int numberOfSeconds = duration;
if (timeSeries.length >0)
old_goalpost = timeSeries[0]+duration-1;
else
numberOfSeconds=0;
if (timeSeries.length >0)
for (i=1;i<timeSeries.length;i++)
{
new_goalpost = timeSeries[i]+duration-1;
diff = (new_goalpost - old_goalpost)>duration?duration:((new_goalpost - old_goalpost));
numberOfSeconds = numberOfSeconds +diff;
old_goalpost = new_goalpost;
}
return numberOfSeconds;
}
}
And it has passed all the test cases.
If you want, this is the link to the question https://leetcode.com/problems/teemo-attacking/
this code is 99.97% faster but memory heavy
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int i =0,old_goalpost=0,new_goalpost=0 ,diff=0;
int numberOfSeconds = duration;
if (timeSeries.length >0)
old_goalpost = timeSeries[0]+duration-1;
else
numberOfSeconds=0;
if (timeSeries.length >0)
for (i=1;i<timeSeries.length;i++)
{
new_goalpost = timeSeries[i]+duration-1;
diff = (new_goalpost - old_goalpost)>duration?duration:((new_goalpost - old_goalpost));
numberOfSeconds = numberOfSeconds +diff;
old_goalpost = new_goalpost;
}
return numberOfSeconds;
}
}