版权声明:本文为博主原创文章,欢迎大家转载,但是要注明我的文章地址。 https://blog.csdn.net/program_developer/article/details/83010240
题目链接:
题目描述:
题目:输入一个整型数组,数组里面有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
牛客网上的题目描述:
解题思路:
(1)举例分析数组的规律、
已经AC的代码:
public class greatestSumOfSubArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {-2, -8, -1, -5, -9};
int[] arr1 = {1, -2, 3, 10, -4, 7, 2, -5};
System.out.println(FindGreatestSumOfSubArray(arr1));
}
public static int FindGreatestSumOfSubArray(int[] array) {
if(array == null && array.length <= 0) {
return 0;
}
int Maxsum = Integer.MIN_VALUE;
int currentSum = 0;
for(int i=0; i<array.length; i++) {
currentSum += array[i];
if(currentSum < array[i]) {
currentSum = array[i];
}
if(currentSum > Maxsum) {
Maxsum = currentSum;
}
}
return Maxsum;
}
}
(2)动态规划法
设f(i)表示以第i个数字结尾的子数组的最大和,那么我们可以写出状态转移方程:
已经AC的代码:
public class greatestSumOfSubArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {-2, -8, -1, -5, -9};
int[] arr1 = {1, -2, 3, 10, -4, 7, 2, -5};
System.out.println(FindGreatestSumOfSubArray(arr1));
}
public static int FindGreatestSumOfSubArray(int[] array) {
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
for(int i=0; i<array.length; i++) {
if(currentSum <= 0) {
currentSum = array[i];
}else {
currentSum += array[i];
}
if(currentSum > maxSum) {
maxSum = currentSum;
}
}
return maxSum;
}
}