Greatest Sum Divisible by Three

MediumDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an array nums of positive integers, choose any subset of its elements (possibly empty) so that their sum is divisible by 3. Return the largest such sum. The empty subset has sum 0, so the answer is always at least 0.

Examples

Input: nums = [3,6,5,1,8]
Output: 18
Pick 3, 6, 1, and 8.
Input: nums = [4]
Output: 0
4 is not divisible by 3, so pick nothing.
Input: nums = [1,2,3,4,4]
Output: 12
Pick 1, 3, 4, and 4.

Constraints

  • `1 <= nums.length <= 4 * 10^4`
  • `1 <= nums[i] <= 10^4`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems