Leetcode

4 Keys Keyboard

Approach 1: Top-down

  • Time:O(N^2)
  • Space:O(N)

C++

class Solution {
 public:
  int maxA(int N) {
    int ans = N;

    for (int i = 1; i <= N - 3; ++i)
      ans = max(ans, maxA(i) * (N - i - 1));

    return ans;
  }
};

JAVA

class Solution {
  public int maxA(int N) {
    int ans = N;

    for (int i = 1; i <= N - 3; ++i)
      ans = Math.max(ans, maxA(i) * (N - i - 1));

    return ans;
  }
}

Approach 2: Bottom-up

  • Time:O(N^2)
  • Space:O(N)

C++

class Solution {
 public:
  int maxA(int N) {
    // dp[i] := max 'A' can be printed w/ i pressings
    vector<int> dp(N + 1);

    // 'A' * i
    iota(begin(dp), end(dp), 0);

    for (int i = 0; i <= N; ++i)
      for (int j = 0; j <= i - 3; ++j)
        dp[i] = max(dp[i], dp[j] * (i - j - 1));

    return dp[N];
  }
};

JAVA

class Solution {
  public int maxA(int N) {
    // dp[i] := max 'A' can be printed w/ i pressings
    int[] dp = new int[N + 1];

    for (int i = 0; i <= N; ++i) {
      dp[i] = i; // 'A' * i
      for (int j = 0; j <= i - 3; ++j)
        dp[i] = Math.max(dp[i], dp[j] * (i - j - 1));
    }

    return dp[N];
  }
}