最大子数组
题:给出一个整数数组nums,找到一个有最大和的连续子数组(至少包含一个值),并返回最大值
例:Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
思路:这是我研究生复试机试的最后一题,只是多了一些输出,要求输出最大子数组的起始点索引和末尾索引。虽然中间没有接触到这道题,但是现在再次做到此题,感觉之前在考试时做的不理想真的是不应该,最简答的方法就是使用暴力破解,但是时间复杂度太高。
代码:
class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0];
//int sum = 0;
for(int i = 0;i < nums.length;i++){
for(int j = i;j < nums.length;j++){
int sum = 0;
for(int z = i;z <= j;z++){
sum += nums[z];
}
max = Math.max(max,sum);
}
}
return max;
}
}
时间复杂度:O(n3),空间复杂度:O(1)