Skip to content

1262. Greatest Sum Divisible by Three 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int maxSumDivThree(vector<int>& nums) {
    vector<int> dp(3);  // dp[i] := the maximum sum so far s.t. sum % 3 == i

    for (const int num : nums)
      for (const int sum : vector<int>(dp))
        dp[(sum + num) % 3] = max(dp[(sum + num) % 3], sum + num);

    return dp[0];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int maxSumDivThree(int[] nums) {
    int[] dp = new int[3]; // dp[i] := the maximum sum so far s.t. sum % 3 == i

    for (final int num : nums)
      for (final int sum : dp.clone())
        dp[(sum + num) % 3] = Math.max(dp[(sum + num) % 3], sum + num);

    return dp[0];
  }
}