Determine which column contains the maximum sum of its elements

carphatianMayklo :

I would like to know, how to find out which column in the 2D-array has got the largest sum. How would I approach this?

    public static void main(String args[]) {
        int[][] array = {
                { 132, 154, 118 },
                { 355, 101,  50 },
                { 432, 143, 365 },
                { 462, 234, 185 }
        };
    } 
itzFlubby :

You could go with a nested for loop

int maxCol = 0;
int valOfMaxCol = 0;
for(int i = 0; i < 3; i++){
    int sum = 0;
    for(int j = 0; j < array.length; j++){
      sum += array[j][i];
    }
    if(sum > valOfMaxCol){
        valOfMaxCol = sum;
        maxCol = i;
    }
}
System.out.println("Max Col is " + (maxCol + 1) + " with the value " + valOfMaxCol); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=341100&siteId=1