左神面试算法整理--最大子串和

来源:互联网 发布:万网域名cname怎么设置 编辑:程序博客网 时间:2024/06/07 02:03



算法思想:



当一个数组中有一个子串它的累加和是最大的,那么它不存在一个前缀或是后缀是负数,如果存在的话,它就不是最大和,因为出去前缀或是后缀他的值会更大。因此此题的解题思路就是找有效的前缀,只要前缀是大于0的,都有可能成为最大和的一部分,当前缀小于0时,就将其舍弃,从下一位置重新开始。在寻找的过程中,用max记录前缀出现的最大值,这个最大值,也就是最大累加和值。

JAVA版

package problems_2017_07_26;


public class Problem_03_SubArrayMaxSum {


public static int maxSum(int[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
int max = Integer.MIN_VALUE;
int cur = 0;
for (int i = 0; i != arr.length; i++) {
cur += arr[i];
max = Math.max(max, cur);
cur = cur < 0 ? 0 : cur;
}
return max;
}


public static void printArray(int[] arr) {
for (int i = 0; i != arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}


public static void main(String[] args) {
int[] arr1 = { -2, -3, -5, 40, -10, -10, 100, 1 };
System.out.println(maxSum(arr1));


int[] arr2 = { -2, -3, -5, 0, 1, 2, -1 };
System.out.println(maxSum(arr2));


int[] arr3 = { -2, -3, -5, -1 };
System.out.println(maxSum(arr3));


}


}


C++版

#include<iostream>
#include<stack>
#include<string>


using namespace std;


int fun(int* a,int n)
{
int max=0;
int count=0;
for(int i=0;i<n;i++)
{
count+=a[i];
if(count>max)
max=count;
if(count<0)
count=0;

}
return max;
}


int main()
{
int a[7]={1,-1,3,5,-2,6,-1};


int result=fun(a,7);


cout<<result<<endl;
system("pause");
return 0;
}