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



算法思想:



当一个数组中有一个子串它的累加和是最大的,那么它不存在一个前缀或是后缀是负数,如果存在的话,它就不是最大和,因为出去前缀或是后缀他的值会更大。因此此题的解题思路就是找有效的前缀,只要前缀是大于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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值