LeetCode 1262: Greatest Sum Divisible by Three
Problem Description
Explanation:
To find the maximum sum of elements in the array that is divisible by three, we can use dynamic programming to keep track of the maximum sum we can achieve at each step. We will consider three cases: the sum modulo 3 is 0, 1, or 2. By keeping track of these values in the dynamic programming table, we can eventually find the maximum sum that is divisible by three.
- Initialize a 2D dynamic programming array dp of size nums.length + 1 by 3.
- Iterate through each element in the input array nums.
- For each element, update the dynamic programming array based on the three cases mentioned above.
- Return the maximum sum that is divisible by three.
Time Complexity: O(n), where n is the length of the input array. Space Complexity: O(n) since we are using a 2D dynamic programming array of size n by 3.
:
Solutions
class Solution {
public int maxSumDivThree(int[] nums) {
int n = nums.length;
int[][] dp = new int[n + 1][3];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 3; j++) {
dp[i][j] = dp[i - 1][j];
int mod = nums[i - 1] % 3;
int prevMod = (3 + j - mod) % 3;
dp[i][mod] = Math.max(dp[i][mod], dp[i - 1][j] + nums[i - 1]);
}
}
return dp[n][0];
}
}
Loading editor...