# Why "i++" in the for loop will cause Time Limit Exceed?

• Here is my code:

``````public class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0],maxEndingHere = nums[0];
for(int i=1;i<nums.length;i++){
maxEndingHere = Math.max(maxEndingHere+nums[i],nums[i]);
max = Math.max(maxEndingHere,max);
}
return max;
}
}
``````

I receive a "Time Limit Exceed" error when I run it, but if I simply change the for loop to be:

``````for(int i=1;i<nums.length;++i)
``````

The test cases pass properly. Can someone tell me why??

Thank you very much!

• class Solution {
public:
int maxSubArray(vector<int>& nums) {
int size = nums.size();
int max_sum = nums[0];
int sum = nums[0];
if(size == 1) return max_sum;
for (int i = 1; i < size; i++)
{
sum = max(nums[i], sum + nums[i]);
cout << "sum:" << sum << endl;
max_sum = max(sum, max_sum);
}
return max_sum;
}

same solution. guess you lack "() " after your nums.length
the correct usage should be nums.length()

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.