maximum subarray whose sum equals 0

后端 未结 12 1397
礼貌的吻别
礼貌的吻别 2020-12-04 08:14

An array contains both positive and negative elements, find the maximum subarray whose sum equals 0.

12条回答
  •  余生分开走
    2020-12-04 08:42

    Hope this help you.

     private static void subArrayZeroSum(int array[] , int findSum){
        Map> map = new HashMap>();
        int sum = 0;
       for(int index = 0 ; index < array.length ; index ++){
           sum +=array[index];
           if(array[index] == findSum){
               System.out.println(" ["+index+"]");
           }
           if(sum == findSum && index > 0){
               System.out.println(" [ 0 , "+index+" ]");
           }
           if(map.containsKey(sum)){
               HashSet set = map.get(sum);
               if(set == null)
                   set = new HashSet();
    
               set.add(index);
               map.put(sum, set);
    
               for(int val : set){
    
                   if(val + 1 != index && (val + 1) < index){
                      System.out.println("["+(val + 1) +","+index+" ]");
                   }
               }
    
            }else{
                HashSet set = map.get(sum);
                   if(set == null)
                       set = new HashSet();
                   set.add(index);
                map.put(sum, set);
            }
       }        
    }
    

提交回复
热议问题