
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Greatest Sum Divisible by Three in C++
Suppose we have an array nums of integers, we need to find the maximum possible sum of elements of the given array such that it is divisible by three. So if the input is like [3,6,5,1,8], then the output will be 18, as the subarray is [3,6,1,8], and the sum is 18, that is divisible by 3.
To solve this, we will follow these steps −
- n := size of nums array
- create one 2d array dp of size (n + 1) x 3
- set dp[0, 0] := 0, dp[0,1] := -inf, dp[0,2] := inf
- for i in range 1 to n;
- x := nums[i - 1]
- for j in range 0 to 2, dp[i, j] := dp[i – 1, j]
- for j in range 0 to 2
- k := (x + j) mod 3
- dp[i, k] := max of dp[i, k] and dp[i – 1, j] + x
- return dp[n, 0]
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxSumDivThree(vector<int>& nums) { int n = nums.size(); int dp[n+1][3]; dp[0][0] = 0; dp[0][1] = INT_MIN; dp[0][2] = INT_MIN; for(int i = 1; i <= n; i++){ int x = nums[i-1]; for(int j = 0; j < 3; j++)dp[i][j] = dp[i-1][j]; for(int j = 0; j < 3; j++){ int k = (x + j) % 3; dp[i][k] = max(dp[i][k],dp[i-1][j] + x); } } return dp[n][0]; } }; main(){ vector<int> v = {3,6,5,1,8}; Solution ob; cout << (ob.maxSumDivThree(v)); }
Input
[3,6,5,1,8]
Output
18
- Related Questions & Answers
- Greatest number divisible by n within a bound in JavaScript
- Largest N digit number divisible by given three numbers in C++
- Number of Groups of Sizes Two Or Three Divisible By 3 in C++
- Sum which is divisible by n in JavaScript
- Count pairs in array whose sum is divisible by K in C++
- Count pairs in array whose sum is divisible by 4 in C++
- Program to make sum divisible by P in Python
- Find the greatest product of three numbers in JavaScript
- Maximize the number of sum pairs which are divisible by K in C++
- Count all sub-arrays having sum divisible by k
- Subarray Sums Divisible by K in C++
- Count rotations divisible by 8 in C++
- Count rotations divisible by 4 in C++
- Finding greatest digit by recursion - JavaScript
- Find permutation of n which is divisible by 3 but not divisible by 6 in C++
Advertisements