Saturday, 18 August 2018

Find maximum sub array of positve number

 public int[] maxset(int[] A) {
       
        long tempSum = 0;
        long finalSum = 0;
        ArrayList<Integer> maxArray = new ArrayList<>();
        ArrayList<Integer> newArray = new ArrayList<>();
 
        for(int i=0;i<A.length;i++) {
            if(A[i]>=0){
                tempSum = tempSum+A[i];
                newArray.add(A[i]);
          
                if(tempSum>finalSum ||( tempSum==finalSum && newArray.size()>maxArray.size())) {
                    finalSum = tempSum;
                    maxArray = (ArrayList<Integer>)newArray.clone();
                    
                }
            }else {
                tempSum = 0;
                 newArray = new ArrayList<>();
                        
            }
        }
       
        int[] list = new int[maxArray.size()];
        for(int i=0;i<maxArray.size();i++) {
            list[i] = maxArray.get(i);
        }
       
        return list;
       
   
    }

input:  int[] arr = {1967513926, 1540383426, -1303455736, -521595368};
output: [1967513926, 1540383426]

input: int[] arr = {0,0,-1,0}
output: [0,0]



No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...