题目:
求一个数组中连续数字之和最大值。其中连续数字可以从末尾到起始值,举例:
数组:1,-2,1,3,-1,3
最大值:7,数组是1,-2,1,3,-1,3
要求:
数组最大长度是100000
值符合[-2000,2000]
计算时间小于100ms
思考:
这个问题相当于:1)以第m个元素开始,以第m-1个元素结束,计算其最大值;2)然后遍历了第[1,n]个最大元素开始的数组后,取最大值。
算法复杂度为n*n
有一些优化点:
1、计算所有元素的值,只需要在计算第一个元素为起始点时即可
2、如果下一个值为非负数,那么可以忽略它作为下一个计算开始值。
单线程的算法实现
问题:在[1,-1,1,-1…]这种循环正负数的数组中,计算时间一直超过100ms
import java.util.ArrayList;
import java.util.concurrent.*;
public class ProfitInfo {
public static final int MAX = 100000;
public int[] mProfits = new int[MAX+1];
public int N;
public ProfitInfo() {
}
public int getMaxProfits() {
int answer = 0;
answer = getProfitFromBeginToEnd(1, N);
return answer;
}
private int getProfitFromBeginToEnd(int begin, int end) {
int currentProfit = mProfits[begin];
int maxProfit = currentProfit;
int[] currentResult = {0,0};
for (int i = begin; i <= end; i++) {
currentResult = getMaxProfitByIndex(i ,begin, end);
currentProfit = currentResult[0];
i = currentResult[1];
if(currentProfit > maxProfit) {