【问题标题】:Print the number of subarrays in an array having negative sum [closed]打印具有负和的数组中子数组的数量[关闭]
【发布时间】:2019-06-01 08:22:23
【问题描述】:
import java.io.*;
import java.util.*;
public class Solution {
    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        int n=scan.nextInt(); //taking input number of elements in the array
        int[] a=new int[n];
        for(int i=0;i<n;i++){
            a[i]=scan.nextInt(); //taking input elements of the array
        }
        int count=0;
        //start point
        for(int i=0;i<n;i++){
            //end point
            for(int j=i;j<n;j++){
                for(int k=i;k<=j;k++){
                    int sum=0;
                    sum+=a[k];  //calculating the sum of subarray
                    if(sum<0)
                    count++;
                }
            }
        }
        System.out.println(count); //printing the no of negative sums 
    }
}

这里有三个嵌套循环,第一个循环定义起始位置,第二个循环定义结束位置,第三个循环用于迭代子数组的元素并计算它们的总和,如果总和小于零,则增加计数。但是使用这段代码我得到了错误的答案。

【问题讨论】:

  • if (sum &lt; 0) count++ 应该在k 循环之后。并且sum 应该在它之前声明。
  • 什么错误答案?
  • @AndyTurner 考虑将其转换为答案。
  • 对于 OP:可以使用一些日志记录或在调试器中逐步运行程序来轻松调试此问题。
  • @khelwood 我没有测试用例,因为我在编码网站上尝试过

标签: java arrays nested-loops


【解决方案1】:

不需要第三个循环

int count = 0;
    for(int i = 0; i < n; i++) { // for start position
        int sum = 0;
        for(int j = i; j < n; j++) { // for end position
            sum += a[j];
            if(sum < 0) {
                count++;
            }
        }
    }
// output count

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多