输入:数组n的大小,整数A [1..n]的数组。 -10 ^ 6 <= A [i] <= 10 ^ 6。
对于所有元素,找到一个具有最大和的子数组,该子数组覆盖该元素(更正式地说,对于每个i,找到最大值A [l] + A [l + 1] +··+ A [r] 在所有索引对l和r中,使得1≤l≤i≤r≤n)。 输出:n个整数,其中第i个整数应等于A中所有覆盖位置i的子数组的最大和。 时限-3秒。
示例: 5
2 -3 -3 -3 2
输出:2 -1 -3 -1 2
我已经写了一个算法,但是速度不够快。如何提高效率?
public class MaximalSumSubarray {
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int q;
q = in.nextInt();
int[] t = new int[q];
for (int i = 0; i < q; ++i) {
t[i] = in.nextInt();
}
long[] result = new long[q];
///
long[] temp = new long[q+1];
for (int i = 0; i < q; i++) {
for (int j = i; j < q; j++) {
temp[j+1] += t[i];
}
}
for (int i = 0; i < q; i++) {
long max = -1000000;
for (int l = 0; l <= i; l++) {
for (int r = i; r < q; r++) {
if (temp[r+1] - temp[l] >= max) {
result[i] = temp[r+1] - temp[l];
max = result[i];
}
}
}
}
////
for (int i = 0; i < result.length; ++i) {
out.print(result[i] + " ");
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}