Maximize the happiness of the groups on the Trip
Last Updated :
11 Jul, 2025
A trip to mystical land is going to be organized in ByteLand, the city of Bytes. Unfortunately, there are limited seats say A and there are N number of groups of people. Every group can have old person o, child c, man m and woman w. The organizing committee wants to maximize the happiness value of the trip. Happiness value of the trip is the sum of the happiness value of all the groups that are going. A group will go for the trip if every member can get a seat (Breaking a group is not a good thing).
- The happiness of child c = 4
- The happiness of woman w = 3
- The happiness of man m = 2
- The happiness of the old person o = 1
The happiness of group G, H(G) = (sum of happiness of people in it) * (number of people in the group).
The happiness of the group ('coow') = (4 + 1 + 1 + 3) * 4 = 36.
Given the groups and the total seating capacity, the task is to maximize the happiness and print the maximized happiness of the groups going on the trip.
Examples:
Input: groups[] = {"mmo", "oo", "cmw", "cc", "c"}, A = 5
Output: 43
Pick these groups ['cmw', 'cc'] to get the maximum profit of (4 + 2 + 3) * 3 + (4 + 4) * 2 = 43
Input: groups[] = {"ccc", "oo", "cm", "mm", "wwo"}, A = 10
Output: 77
Approach: The problem can be considered as a slight modification of the 0-1 knapsack problem. The total seats available can be considered as the size of the knapsack. The happiness of each group can be considered as the profit of each item and the number of people in each group can be considered as the weight of each item. Now similar to the dynamic programming approach for 0-1 knapsack problem apply dynamic programming here to get the maximum happiness.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximized happiness
int MaxHappiness(int A, int N, vector<string> v)
{
string str;
// Two arrays similar to
// 0 1 knapsack problem
int val[N], wt[N], c = 0;
for (int i = 0; i < N; i++) {
str = v[i];
// To store the happiness
// of the current group
c = 0;
for (int j = 0; str[j]; j++) {
// Current person is a child
if (str[j] == 'c')
c += 4;
// Woman
else if (str[j] == 'w')
c += 3;
// Man
else if (str[j] == 'm')
c += 2;
// Old person
else
c++;
}
// Group's happiness is the sum of happiness
// of the people in the group multiplied by
// the number of people
c *= str.length();
val[i] = c;
wt[i] = str.length();
}
// Solution using 0 1 knapsack
int k[N + 1][A + 1];
for (int i = 0; i <= N; i++) {
for (int w = 0; w <= A; w++) {
if (i == 0 || w == 0)
k[i][w] = 0;
else if (wt[i - 1] <= w)
k[i][w] = max(val[i - 1]
+ k[i - 1][w - wt[i - 1]],
k[i - 1][w]);
else
k[i][w] = k[i - 1][w];
}
}
return k[N][A];
}
// Driver code
int main()
{
// Number of seats
int A = 5;
// Groups
vector<string> v = { "mmo", "oo", "cmw", "cc", "c" };
int N = v.size();
cout << MaxHappiness(A, N, v);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the maximized happiness
static int maxHappiness(int A, int N, String[] v)
{
String str;
// Two arrays similar to
// 0 1 knapsack problem
int[] val = new int[N];
int[] wt = new int[N];
int c = 0;
for (int i = 0; i < N; i++)
{
str = v[i];
// To store the happiness
// of the current group
c = 0;
for (int j = 0; j < str.length(); j++)
{
// Current person is a child
if (str.charAt(j) == 'c')
c += 4;
// Woman
else if (str.charAt(j) == 'w')
c += 3;
// Man
else if (str.charAt(j) == 'm')
c += 2;
// Old Person
else
c++;
}
// Group's happiness is the sum of happiness
// of the people in the group multiplie
// the number of people
c *= str.length();
val[i] = c;
wt[i] = str.length();
}
// Solution using 0 1 knapsack
int[][] k = new int[N + 1][A + 1];
for (int i = 0; i <= N; i++)
{
for (int w = 0; w <= A; w++)
{
if (i == 0 || w == 0)
k[i][w] = 0;
else if (wt[i - 1] <= w)
{
k[i][w] = Math.max(val[i - 1]+ k[i - 1][w - wt[i - 1]], k[i-1][w]);
}
else
{
k[i][w] = k[i - 1][w];
}
}
}
return k[N][A];
}
// Driver code
public static void main(String[] args)
{
// Number of seats
int A = 5;
// Groups
String[] v = { "mmo", "oo", "cmw", "cc", "c" };
int N = v.length;
System.out.println(maxHappiness(A, N, v));
}
}
// This code is contributed by Vivek Kumar Singh
Python3
# Python3 implementation of the approach
import numpy as np
# Function to return the maximized happiness
def MaxHappiness(A, N, v) :
# Two arrays similar to
# 0 1 knapsack problem
val = [0] * N; wt = [0] * N; c = 0;
for i in range(N) :
string = v[i];
# To store the happiness
# of the current group
c = 0;
for j in range(len(string)) :
# Current person is a child
if (string[j] == 'c') :
c += 4;
# Woman
elif (string[j] == 'w') :
c += 3;
# Man
elif (string[j] == 'm') :
c += 2;
# Old person
else :
c += 1;
# Group's happiness is the sum of happiness
# of the people in the group multiplied by
# the number of people
c *= len(string);
val[i] = c;
wt[i] = len(string);
# Solution using 0 1 knapsack
k = np.zeros((N + 1, A + 1))
for i in range(N + 1) :
for w in range(A + 1) :
if (i == 0 or w == 0) :
k[i][w] = 0;
elif (wt[i - 1] <= w) :
k[i][w] = max(val[i - 1] +
k[i - 1][w - wt[i - 1]],
k[i - 1][w]);
else :
k[i][w] = k[i - 1][w];
return k[N][A];
# Driver code
if __name__ == "__main__" :
# Number of seats
A = 5;
# Groups
v = [ "mmo", "oo", "cmw", "cc", "c" ];
N = len(v);
print(MaxHappiness(A, N, v));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the maximized happiness
static int maxHappiness(int A, int N,
String[] v)
{
String str;
// Two arrays similar to
// 0 1 knapsack problem
int[] val = new int[N];
int[] wt = new int[N];
int c = 0;
for (int i = 0; i < N; i++)
{
str = v[i];
// To store the happiness
// of the current group
c = 0;
for (int j = 0; j < str.Length; j++)
{
// Current person is a child
if (str[j] == 'c')
c += 4;
// Woman
else if (str[j] == 'w')
c += 3;
// Man
else if (str[j] == 'm')
c += 2;
// Old Person
else
c++;
}
// Group's happiness is the sum of happiness
// of the people in the group multiplie
// the number of people
c *= str.Length;
val[i] = c;
wt[i] = str.Length;
}
// Solution using 0 1 knapsack
int[ , ] k = new int[N + 1, A + 1];
for (int i = 0; i <= N; i++)
{
for (int w = 0; w <= A; w++)
{
if (i == 0 || w == 0)
k[i, w] = 0;
else if (wt[i - 1] <= w)
{
k[i, w] = Math.Max(val[i - 1]+
k[i - 1, w - wt[i - 1]],
k[i - 1, w]);
}
else
{
k[i, w] = k[i - 1, w];
}
}
}
return k[N, A];
}
// Driver code
public static void Main()
{
// Number of seats
int A = 5;
// Groups
String[] v = { "mmo", "oo", "cmw", "cc", "c" };
int N = v.Length;
Console.WriteLine(maxHappiness(A, N, v));
}
}
// This code is contributed by Mohit kumar 29
JavaScript
<script>
// Javascript program for the above approach
// Function to return the maximized happiness
function maxHappiness(A, N, v) {
let str;
// Two arrays similar to
// 0 1 knapsack problem
let val = Array.from({length: N}, (_, i) => 0);
let wt = Array.from({length: N}, (_, i) => 0);
let c = 0;
for (let i = 0; i < N; i++)
{
str = v[i];
// To store the happiness
// of the current group
c = 0;
for (let j = 0; j < str.length; j++)
{
// Current person is a child
if (str[j] == 'c')
c += 4;
// Woman
else if (str[j] == 'w')
c += 3;
// Man
else if (str[j] == 'm')
c += 2;
// Old Person
else
c++;
}
// Group's happiness is the sum of happiness
// of the people in the group multiplie
// the number of people
c *= str.length;
val[i] = c;
wt[i] = str.length;
}
// Solution using 0 1 knapsack
let k = new Array(N + 1);
for (var i = 0; i < k.length; i++) {
k[i] = new Array(2);
}
for (let i = 0; i <= N; i++)
{
for (let w = 0; w <= A; w++)
{
if (i == 0 || w == 0)
k[i][w] = 0;
else if (wt[i - 1] <= w)
{
k[i][w] = Math.max(val[i - 1]+ k[i - 1][w - wt[i - 1]], k[i-1][w]);
}
else
{
k[i][w] = k[i - 1][w];
}
}
}
return k[N][A];
}
// Driver Code
// Number of seats
let A = 5;
// Groups
let v = [ "mmo", "oo", "cmw", "cc", "c" ];
let N = v.length;
document.write(maxHappiness(A, N, v));
// This code is contributed by sanjoy_62.
</script>
Time Complexity: O(N *(L + A))
Auxiliary Space: O(N * A), where N is the size of the vector of strings, L is the maximum length of a string in the vector and A is a given input.
Efficient approach : Space optimization
In previous approach the current value K[i][w] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.
Implementation steps:
- Create a 1D vector dp of size A+1 and initialize it with 0.
- Set a base case by initializing the values of DP .
- Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
- Update Dp by iterating through subproblems
- At last return and print the final answer stored in dp[A] .
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximized happiness
int MaxHappiness(int A, int N, vector<string> v)
{
string str;
// Two arrays similar to
// 0 1 knapsack problem
int val[N], wt[N], c = 0;
for (int i = 0; i < N; i++) {
str = v[i];
// To store the happiness
// of the current group
c = 0;
for (int j = 0; str[j]; j++) {
// Current person is a child
if (str[j] == 'c')
c += 4;
// Woman
else if (str[j] == 'w')
c += 3;
// Man
else if (str[j] == 'm')
c += 2;
// Old person
else
c++;
}
// Group's happiness is the sum of happiness
// of the people in the group multiplied by
// the number of people
c *= str.length();
val[i] = c;
wt[i] = str.length();
}
// Solution using 0 1 knapsack
vector<int> dp(A + 1 , 0);
for (int i = 1; i <= N; i++) {
for (int w = A; w >= wt[i - 1]; w--) {
dp[w] = max(val[i - 1] + dp[w - wt[i - 1]], dp[w]);
}
}
return dp[A];
}
// Driver code
int main()
{
// Number of seats
int A = 5;
// Groups
vector<string> v = { "mmo", "oo", "cmw", "cc", "c" };
int N = v.size();
cout << MaxHappiness(A, N, v);
return 0;
}
Java
import java.util.*;
public class Main {
public static int maxHappiness(int A, int N, List<String> v) {
String str;
int[] val = new int[N];
int[] wt = new int[N];
int c;
for (int i = 0; i < N; i++) {
str = v.get(i);
c = 0;
for (int j = 0; j < str.length(); j++) {
char ch = str.charAt(j);
if (ch == 'c')
c += 4;
else if (ch == 'w')
c += 3;
else if (ch == 'm')
c += 2;
else
c++;
}
c *= str.length();
val[i] = c;
wt[i] = str.length();
}
int[] dp = new int[A + 1];
for (int i = 1; i <= N; i++) {
for (int w = A; w >= wt[i - 1]; w--) {
dp[w] = Math.max(val[i - 1] + dp[w - wt[i - 1]], dp[w]);
}
}
return dp[A];
}
public static void main(String[] args) {
int A = 5;
List<String> v = Arrays.asList("mmo", "oo", "cmw", "cc", "c");
int N = v.size();
System.out.println(maxHappiness(A, N, v));
}
}
Python3
def MaxHappiness(A, N, v) -> int:
# Two lists similar to 0-1 knapsack problem
val = [0] * N
wt = [0] * N
for i in range(N):
# To store the happiness of the current group
c = 0
for j in range(len(v[i])):
# Current person is a child
if v[i][j] == 'c':
c += 4
# Woman
elif v[i][j] == 'w':
c += 3
# Man
elif v[i][j] == 'm':
c += 2
# Old person
else:
c += 1
# Group's happiness is the sum of happiness of the people
# in the group multiplied by the number of people
c *= len(v[i])
val[i] = c
wt[i] = len(v[i])
# Solution using 0-1 knapsack
dp = [0] * (A + 1)
for i in range(1, N + 1):
for w in range(A, wt[i - 1] - 1, -1):
dp[w] = max(val[i - 1] + dp[w - wt[i - 1]], dp[w])
return dp[A]
# Driver code
if __name__ == '__main__':
# Number of seats
A = 5
# Groups
v = ["mmo", "oo", "cmw", "cc", "c"]
N = len(v)
print(MaxHappiness(A, N, v))
C#
using System;
public class MainClass {
public static int MaxHappiness(int A, int N, string[] v)
{
// Two arrays similar to 0-1 knapsack problem
int[] val = new int[N];
int[] wt = new int[N];
for (int i = 0; i < N; i++) {
// To store the happiness of the current group
int c = 0;
for (int j = 0; j < v[i].Length; j++) {
// Current person is a child
if (v[i][j] == 'c') {
c += 4;
}
// Woman
else if (v[i][j] == 'w') {
c += 3;
}
// Man
else if (v[i][j] == 'm') {
c += 2;
}
// Old person
else {
c += 1;
}
}
// Group's happiness is the sum of happiness of
// the people in the group multiplied by the
// number of people
c *= v[i].Length;
val[i] = c;
wt[i] = v[i].Length;
}
// Solution using 0-1 knapsack
int[] dp = new int[A + 1];
for (int i = 1; i <= N; i++) {
for (int w = A; w >= wt[i - 1]; w--) {
dp[w] = Math.Max(
val[i - 1] + dp[w - wt[i - 1]], dp[w]);
}
}
return dp[A];
}
public static void Main()
{
// Number of seats
int A = 5;
// Groups
string[] v = { "mmo", "oo", "cmw", "cc", "c" };
int N = v.Length;
Console.WriteLine(
MaxHappiness(A, N, v)); // Output: 21
}
}
JavaScript
// Function to return the maximized happiness
function MaxHappiness(A, N, v) {
let val = [];
let wt = [];
let c = 0;
for (let i = 0; i < N; i++) {
let str = v[i];
// To store the happiness of the current group
c = 0;
for (let j = 0; j < str.length; j++) {
// Current person is a child
if (str[j] === 'c')
c += 4;
// Woman
else if (str[j] === 'w')
c += 3;
// Man
else if (str[j] === 'm')
c += 2;
// Old person
else
c++;
}
// Group's happiness is the sum of happiness
// of the people in the group multiplied by
// the number of people
c *= str.length;
val[i] = c;
wt[i] = str.length;
}
// Solution using 0/1 knapsack
let dp = new Array(A + 1).fill(0);
for (let i = 1; i <= N; i++) {
for (let w = A; w >= wt[i - 1]; w--) {
dp[w] = Math.max(val[i - 1] + dp[w - wt[i - 1]], dp[w]);
}
}
return dp[A];
}
// Driver code
function main() {
// Number of seats
let A = 5;
// Groups
let v = ["mmo", "oo", "cmw", "cc", "c"];
let N = v.length;
console.log(MaxHappiness(A, N, v));
}
main();
Time Complexity: O(N *(L + A))
Auxiliary Space: O(A)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem