
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Greatest number divisible by n within a bound in JavaScript
- Determine the greatest four-digit number which is exactly divisible by 10,12,16.?
- Sum which is divisible by n in JavaScript
- Determine the greatest 3 digit number exactly divisible by 8, 10, and 12.
- How many three digit numbers are divisible by 7?
- Program to make sum divisible by P in Python
- Largest N digit number divisible by given three numbers in C++
- Find the greatest 5 digit number that is exactly divisible by 22,25 and 30
- How many three digit natural numbers are divisible by 7?
- Find the greatest 3 digit number that is exactly divisible by 6 15 and 21
- Find the greatest number of 6 digits exactly divisible by 24, 15 and 36./p>
- Count all sub-arrays having sum divisible by k
- Number of Groups of Sizes Two Or Three Divisible By 3 in C++
- Find the greatest 3 digit number which is divisible by the number 4 ,5 and 6.
- Count pairs in array whose sum is divisible by K in C++

Advertisements