我正在尝试使用具有O(n ^ 2)复杂度的BruteForce技术来解决子阵列问题。该代码适用于小型数据集,但由于某些原因,它不适合大数据。我在逻辑上做错了什么。有人可以帮我这个。
问题解释: -
示例输入: -
1
50 1804289384
846930887 1681692778 1714636916 1957747794 424238336 719885387 1649760493 596516650 1189641422 1025202363 1350490028 783368691 1102520060 2044897764 1967513927 1365180541 1540383427 304089173 1303455737 35005212 521595369 294702568 1726956430 336465783 861021531 278722863 233665124 2145174068 468703136 1101513930 1801979803 1315634023 635723059 1369133070 1125898168 1059961394 2089018457 628175012 1656478043 1131176230 1653377374 859484422 1914544920 608413785 756898538 1734575199 1973594325 149798316 2038664371 1129566414
预期产出: -
1802192837
实际输出(我得到的): -
1802467240
代码: -
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static long maximumSum(long[] a, long m) {
long sum = 0;
long val = 0;
for ( int i=0;i<a.length;i++ ) {
for( int j=i;j<a.length;j++ ) {
val = val + a[i];
if( val%m > sum )
sum = val%m;
}
val = 0;
}
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int a0 = 0; a0 < q; a0++){
int n = in.nextInt();
long m = in.nextLong();
long[] a = new long[n];
for(int a_i = 0; a_i < n; a_i++){
a[a_i] = in.nextLong();
}
long result = maximumSum(a, m);
System.out.println(result);
}
in.close();
}
}
编译成功但获得如下运行时异常: -
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Solution.main(Solution.java:29)
答案 0 :(得分:1)
我认为J循环是一个问题,你用相同的元素填充整个子数组
<ul id="socialnavlist" class="clearfix pull-right">