1262. Greatest Sum Divisible by Three #2454
-
|
Topics: Given an integer array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the maximum possible sum of elements in an array such that the sum is divisible by three. The approach involves using dynamic programming to keep track of the maximum sums that yield remainders 0, 1, and 2 when divided by 3 as we iterate through the array. Approach
Let's implement this solution in PHP: 1262. Greatest Sum Divisible by Three <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maxSumDivThree($nums) {
$dp = [0, -PHP_INT_MAX, -PHP_INT_MAX];
foreach ($nums as $num) {
$r = $num % 3;
$temp = $dp;
for ($i = 0; $i < 3; $i++) {
if ($temp[$i] != -PHP_INT_MAX) {
$newRem = ($i + $r) % 3;
$dp[$newRem] = max($dp[$newRem], $temp[$i] + $num);
}
}
}
return $dp[0];
}
// Test cases
echo maxSumDivThree([3,6,5,1,8]) . "\n"; // Output: 18
echo maxSumDivThree([4]) . "\n"; // Output: 0
echo maxSumDivThree([1,2,3,4,4]) . "\n"; // Output: 12
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to find the maximum possible sum of elements in an array such that the sum is divisible by three. The approach involves using dynamic programming to keep track of the maximum sums that yield remainders 0, 1, and 2 when divided by 3 as we iterate through the array.
Approach
Dynamic Programming State Initialization: We maintain a state array
dpof size 3, where:dp[0]stores the maximum sum that is divisible by 3.dp[1]stores the maximum sum that leaves a remainder of 1 when divided by 3.dp[2]stores the maximum sum that leaves a remainder of 2 when divided by 3.Initialization: Initially,
dp[0]is set to 0 (since a sum of 0 is divisible by 3), anddp[1]anddp[2]are set to…