Advertisement
ogv

Untitled

ogv
Nov 13th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. // Runtime: 1 ms, faster than 40.06% of Java online submissions for Score After Flipping Matrix.
  2. class Solution {
  3.     int[][] a;
  4.     int m;
  5.     int n;
  6.     public int matrixScore(int[][] A) {
  7.         a = A;
  8.         m = a.length;
  9.         n = a[0].length;
  10.        
  11.        
  12.         for (int r = 0; r < m; r++)
  13.             if (a[r][0] == 0) flipRow(r);
  14.        
  15.         int max = opt(0);
  16.        
  17.         for (int r = 0; r < m; r++)
  18.             flipRow(r);
  19.        
  20.         max = Math.max(max, opt(0));
  21.         return max;
  22.     }
  23.    
  24.     private int opt(int c){
  25.         if (c == n) return score();
  26.        
  27.         int ones = 0;
  28.         for (int r = 0; r < m; r++)
  29.             if (a[r][c] == 1) ones++;
  30.        
  31.         int max = 0;
  32.         if (ones >= m/2){
  33.             max = Math.max(max, opt(c+1));
  34.         }
  35.         if (ones <= m/2) {
  36.             flipColumn(c);
  37.             max = Math.max(max, opt(c+1));
  38.             flipColumn(c);
  39.         }
  40.         return max;
  41.     }
  42.    
  43.     private int score() {
  44.         int sum = 0;
  45.        
  46.         for (int r = 0; r < m; r++) {
  47.             int num = 0;
  48.             int p = 1;
  49.             for (int c = n-1; c >= 0; c--){
  50.                 if (a[r][c] == 1) num += p;
  51.                 p <<= 1;
  52.             }
  53.             sum += num;
  54.         }
  55.        
  56.         return sum;
  57.     }
  58.    
  59.     private void flipColumn(int c) {
  60.         for (int r = 0; r < m; r++) a[r][c] = 1 - a[r][c];
  61.     }
  62.    
  63.     private void flipRow(int r) {
  64.         for (int c = 0; c < n; c++) a[r][c] = 1 - a[r][c];
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement