Data Structures in Java/Must Know Questions

maximum sum subrray

cat_no2 2021. 12. 1. 14:10

the maximum sum of contiguous subarray

method returning sum

max_sum = Integer.MIN_VALUE;

Brute Force algorithm 

iterate every possibility available

 

double nested for loop - worst 
update max_sum 

for(int i=0; i<a.length; i++){
for(int j=i; j<a.length-1; j++){
    
    
    }
}

//do we want to start over with a new one or want to add it to current max?
when adding the next one is smaller than current then dont add, start over. 
curr_sum + new element vs. new element 
// -2 2 5 -11 6 
//we need max 
int arrayMaxConsecutiveSum2(int [] inputArray){
	int max_sum = inputArray[0];		 
    int curr_sum = max_sum; 	//init 
    	for(int i=1; i<inputArray.length; i++){			
        	//starting over by setting curr_sum to that element vs. adding to 
        	curr_sum = Math.max(inputArray[i], inputArray[i] + curr_sum); 		
        	max_sum = Math.max(max_sum, curr_sum); 		
        }
        return max_sum; 
}

 

 

 

 

'Data Structures in Java > Must Know Questions' 카테고리의 다른 글

longestPalindrome  (0) 2021.12.01
firstDuplicate  (0) 2021.12.01
firstNonRepeatingCharacter  (0) 2021.12.01
sumOfTwo  (0) 2021.11.30
rotateImage  (0) 2021.11.30