Kos*_*asA 2 java algorithm nested
我正在玩codefight,但我真的坚持以下有效的问题.
问题:
给定整数n,l和r,找到将n表示为两个整数A和B之和的方法的数量,使得l≤A≤B≤r.
示例:
对于n = 6,l = 2且r = 4,输出应为countSumOfTwoRepresentations2(n,l,r)= 2.只有两种方法将6写为A + B,其中2≤A≤B≤ 4:6 = 2 + 4和6 = 3 + 3.
这是我的代码.它通过了所有单元测试,但在隐藏的测试中失败了.有人能以某种方式指导我吗?提前致谢.
public static int countSumOfTwoRepresentations2(int n, int l, int r) {
int nrOfWays = 0;
for(int i=l;i<=r;i++)
{
for(int j=i;j<=r;j++)
{
if(i+j==n)
nrOfWays++;
}
}
return nrOfWays;
}
Run Code Online (Sandbox Code Playgroud)
好吧,没有必要进行如此庞大的计算...这很容易计算:
public static int count(int n, int l, int r) {
if (l > n/2)
return 0;
return Math.min(n/2 - l, r - n/2) + ((n%2 == 1) ? 0 : 1);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止通过我所有的测试.对于正面和负面也是如此.