Question
Given an array, find the longest continuous sub-array which has maximum sum.
My Approach
First, I solved this problem using dynamic programming which effectively solved the problem in \$O(n)\$ time as opposed to the brute force approach. For each iteration, I checked if the sum is less than 0, and if true, I ran a new sum whenever the sum became less than 0.
Also, I kept track of the current maximum in each iteration.
class Solution
{
public int maxSubArray(int[] nums)
{
/*
* get the array size.
*/
int size = nums.length;
/*
* initialize the variables to the first index of the array.
*/
int sum = nums[0];
int max = nums[0];
/*
* iterate using a loop from 1 to n-1.
* set sum to 0 if current is less than 0.
* for negative results, no need to add sum as the largest sum is the smallest negative number itself.
* update max if sum is greater.
*/
for (int i = 1; i < size; i++)
{
if (sum < 0)
sum = 0;
sum += nums[i];
if (sum > max)
max = sum;
}
return max;
}
}
As you can see from the above, I have kept the code as compact as possible. I also stored the array length also in a variable for faster execution. And the solution is linear time.
Issues
- When I submit on LeetCode, I am told that my code is only 17% faster as compared to the rest of Java submissions for the same problem.
- How do I make this code more optimised (or rather, is there any way to optimise this code even more?)
- Is there a better/different approach to this problem?
- I haven't used any Java APIs, library functions etc. then could anyone please tell me where is the time being consumed (or rather, which is the most costly operation in my algorithm and is there any way to reduce the costly operation?)
Notes
The solution is correct as it passed all 200 test cases! (It's just that it is slow).
- To find the required sub-array, I need to iterate over the array at least once just to see if my sum can be maximised. In such a case, the minimum time has to be linear time and if this observation were true, then all the other faster solutions must run at least linear time. Again, if the above were true, then it means the faster solutions are using techniques to make the execution faster despite it being linear time, right?
maxSum = ary => Math.max(...ary.map(a => a.reduce((acc, x) => acc + x, 0)))
. Maybe the same idea could be translated to java. \$\endgroup\$