0971-0980

971. Flip Binary Tree To Match Preorder Traversal $\star\star$

972. Equal Rational Numbers $\star\star\star$

973. K Closest Points to Origin $\star\star$

974. Subarray Sums Divisible by K $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int subarraysDivByK(vector<int>& A, int K) {
    int ans = 0;
    int presum = 0;
    vector<int> count(K);
    count[0] = 1;

    for (int a : A) {
      presum = (presum + a % K + K) % K;
      ans += count[presum];
      ++count[presum];
    }

    return ans;
  }
};

975. Odd Even Jump $\star\star\star$

976. Largest Perimeter Triangle $\star$

977. Squares of a Sorted Array $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<int> sortedSquares(vector<int>& A) {
    int n = A.size();
    int l = 0;
    int r = n - 1;
    vector<int> ans(n);

    while (l <= r)
      ans[--n] = abs(A[l]) > abs(A[r]) ? A[l] * A[l++] : A[r] * A[r--];

    return ans;
  }
};

978. Longest Turbulent Subarray $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int maxTurbulenceSize(vector<int>& A) {
    int ans = 1;
    int increasing = 1;
    int decreasing = 1;

    for (int i = 1; i < A.size(); ++i) {
      if (A[i] > A[i - 1]) {
        increasing = decreasing + 1;
        decreasing = 1;
      } else if (A[i] < A[i - 1]) {
        decreasing = increasing + 1;
        increasing = 1;
      } else {
        increasing = 1;
        decreasing = 1;
      }
      ans = max(ans, max(increasing, decreasing));
    }

    return ans;
  }
};

979. Distribute Coins in Binary Tree $\star\star$

980. Unique Paths III $\star\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
 public:
  int uniquePathsIII(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();

    int ans = 0;
    int empty = 1;
    int sx;
    int sy;

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        if (grid[i][j] == 0) {
          ++empty;
        } else if (grid[i][j] == 1) {
          sx = i;
          sy = j;
        } else if (grid[i][j] == 2) {
          ex = i;
          ey = j;
        }
      }

    dfs(grid, empty, sx, sy, ans);

    return ans;
  }

 private:
  int ex;
  int ey;

  void dfs(vector<vector<int>>& grid, int empty, int i, int j, int& ans) {
    if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() ||
        grid[i][j] < 0)
      return;
    if (i == ex && j == ey) {
      if (empty == 0) ++ans;
      return;
    }

    grid[i][j] = -2;
    dfs(grid, empty - 1, i + 1, j, ans);
    dfs(grid, empty - 1, i - 1, j, ans);
    dfs(grid, empty - 1, i, j + 1, ans);
    dfs(grid, empty - 1, i, j - 1, ans);
    grid[i][j] = 0;
  }
};