Sum over Subsets | Dynamic Programming - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Number of ordered pairs such that (Ai & Aj) = 0
Sum over Subsets | Dynamic Programming
Dynamic Programming on Trees | Set-1
Dynamic Programming on Trees | Set 2
Top 20 Dynamic Programming Interview Questions
Longest Common Subsequence | DP-4
Maximum size rectangle binary sub-matrix with all 1s
Maximum size square sub-matrix with all 1s
Longest Increasing Subsequence | DP-3
Longest Increasing Subsequence Size (N log N)
Median in a stream of integers (running integers)
Median of Stream of Running Integers using STL
Minimum product of k integers in an array of positive Integers
K-th Largest Sum Contiguous Subarray
K maximum sum combinations from two arrays
K maximum sums of overlapping contiguous sub-arrays
K maximum sums of non-overlapping contiguous sub-arrays
k smallest elements in same order using O(1) extra space
Find k pairs with smallest sums in two arrays
k-th smallest absolute difference of two elements in an array
Find Second largest element in an array
Find the smallest and second smallest elements in an array
Maximum and minimum of an array using minimum number of comparisons
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
LRU Cache Implementation
Red-Black Tree | Set 1 (Introduction)
Introduction of B-Tree
Segment Tree | Set 1 (Sum of given range)
Agents in Artificial Intelligence
Number of ordered pairs such that (Ai & Aj) = 0
Sum over Subsets | Dynamic Programming
Dynamic Programming on Trees | Set-1
Dynamic Programming on Trees | Set 2
Top 20 Dynamic Programming Interview Questions
Longest Common Subsequence | DP-4
Maximum size rectangle binary sub-matrix with all 1s
Maximum size square sub-matrix with all 1s
Longest Increasing Subsequence | DP-3
Longest Increasing Subsequence Size (N log N)
Median in a stream of integers (running integers)
Median of Stream of Running Integers using STL
Minimum product of k integers in an array of positive Integers
K-th Largest Sum Contiguous Subarray
K maximum sum combinations from two arrays
K maximum sums of overlapping contiguous sub-arrays
K maximum sums of non-overlapping contiguous sub-arrays
k smallest elements in same order using O(1) extra space
Find k pairs with smallest sums in two arrays
k-th smallest absolute difference of two elements in an array
Find Second largest element in an array
Find the smallest and second smallest elements in an array
Maximum and minimum of an array using minimum number of comparisons
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
LRU Cache Implementation
Red-Black Tree | Set 1 (Introduction)
Introduction of B-Tree
Segment Tree | Set 1 (Sum of given range)
Agents in Artificial Intelligence
Difficulty Level :
Hard
Prerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ∑Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bitwise subset of mask x, if x&i==i.Examples:  
Input: A[] = {7, 12, 14, 16}  ,  n = 2
Output: 7, 19, 21, 49
Explanation: There will be 4 values of x: 0,1,2,3
So, we need to calculate F(0),F(1),F(2),F(3).
Now, F(0) = A0 = 7 
F(1) =  A0 + A1 = 19
F(2) = A0 + A2 = 21
F(3) = A0 + A1 + A2 + A3 = 49

Input: A[] = {7, 11, 13, 16}  ,  n = 2
Output: 7, 18, 20, 47 
Explanation: There will be 4 values of x: 0,1,2,3
So, we need to calculate F(0),F(1),F(2),F(3).
Now, F(0) = A0 = 7 
F(1) =  A0 + A1 = 18
F(2) = A0 + A2 = 20
F(3) = A0 + A1 + A2 + A3 = 47
 
Brute-Force Approach: Iterate for all the x from 0 to (2n-1) . Calculate the bitwise subsets of all the x and sum it up for every x.Time-Complexity: O(4^n)Below is the implementation of above idea: 
C++
Java
Python3
C#
PHP
Javascript
// CPP program for brute force// approach of SumOverSubsets DP#include <bits/stdc++.h>using namespace std; // function to print the sum over subsets valuevoid SumOverSubsets(int a[], int n) {   // array to store the SumOverSubsets  int sos[1 << n] = {0};   // iterate for all possible x  for (int x = 0; x < (1 << n); x++) {     // iterate for all possible bitwise subsets    for (int i = 0; i < (1 << n); i++) {       // if i is a bitwise subset of x      if ((x & i) == i)        sos[x] += a[i];    }  }   // printa all the subsets  for (int i = 0; i < (1 << n); i++)    cout << sos[i] << " ";} // Driver Codeint main() {  int a[] = {7, 12, 14, 16};  int n = 2;  SumOverSubsets(a, n);  return 0;}
// Java program for brute force// approach of SumOverSubsets DP class GFG{ // function to print the// sum over subsets valuestatic void SumOverSubsets(int a[], int n) { // array to store the SumOverSubsetsint sos[] = new int [1 << n];  // iterate for all possible xfor (int x = 0; x < (1 << n); x++) {     // iterate for all possible        // bitwise subsets    for (int i = 0; i < (1 << n); i++) {     // if i is a bitwise subset of x    if ((x & i) == i)        sos[x] += a[i];    }} // printa all the subsetsfor (int i = 0; i < (1 << n); i++)    System.out.printf("%d ", sos[i]);} // Driver Codepublic static void main(String[] args) {int a[] = {7, 12, 14, 16};int n = 2;SumOverSubsets(a, n);}} // This code is contributed by// Smitha Dinesh Semwal
# Python 3 program# for brute force# approach of SumOverSubsets DP # function to print the# sum over subsets valuedef SumOverSubsets(a, n):     # array to store    # the SumOverSubsets    sos = [0] * (1 << n)         # iterate for all possible x    for x in range(0,(1 << n)):             # iterate for all        # possible bitwise subsets        for i in range(0,(1 << n)):                  # if i is a bitwise subset of x            if ((x & i) == i):                sos[x] += a[i]                           # printa all the subsets    for i in range(0,(1 << n)):        print(sos[i],end = " ")  # Driver Codea = [7, 12, 14, 16]n = 2SumOverSubsets(a, n) # This code is contributed by# Smitha Dinesh Semwal
// C# program for brute force// approach of SumOverSubsets DPusing System; class GFG {         // function to print the    // sum over subsets value    static void SumOverSubsets(int []a, int n)    {             // array to store the SumOverSubsets        int []sos = new int [1 << n];                          // iterate for all possible x        for (int x = 0; x < (1 << n); x++)        {                     // iterate for all possible            // bitwise subsets            for (int i = 0; i < (1 << n); i++)            {                         // if i is a bitwise subset of x                if ((x & i) == i)                    sos[x] += a[i];            }        }                 // printa all the subsets        for (int i = 0; i < (1 << n); i++)            Console.Write(sos[i] + " ");    }         // Driver function    public static void Main()    {        int []a = {7, 12, 14, 16};        int n = 2;        SumOverSubsets(a, n);    }} // This code is contributed by Sam007
<?php// PHP program for brute force// approach of SumOverSubsets DP // function to print the sum// over subsets valuefunction SumOverSubsets($a, $n){     // array to store the SumOverSubsets    $sos = array(1 << $n);         for($i = 0 ;$i < (1 << $n); $i++)        $sos[$i] = 0;         // iterate for all possible x    for ($x = 0; $x < (1 << $n); $x++)    {             // iterate for all possible        // bitwise subsets        for($i = 0; $i < (1 << $n); $i++)        {                 // if i is a bitwise            // subset of x            if (($x & $i) == $i)                $sos[$x] += $a[$i];        }    }         // printa all the subsets    for ($i = 0; $i < (1 << $n); $i++)        echo $sos[$i] . " ";} // Driver Code$a = array(7, 12, 14, 16);$n = 2;SumOverSubsets($a, $n); // This code is contributed by Sam007?>
<script>    // Javascript program for brute force    // approach of SumOverSubsets DP         // function to print the    // sum over subsets value    function SumOverSubsets(a, n)    {              // array to store the SumOverSubsets        let sos = new Array(1 << n);        sos.fill(0);                            // iterate for all possible x        for (let x = 0; x < (1 << n); x++)        {                      // iterate for all possible            // bitwise subsets            for (let i = 0; i < (1 << n); i++)            {                          // if i is a bitwise subset of x                if ((x & i) == i)                    sos[x] += a[i];            }        }                  // printa all the subsets        for (let i = 0; i < (1 << n); i++)            document.write(sos[i] + " ");    }         let a = [7, 12, 14, 16];    let n = 2;    SumOverSubsets(a, n);         </script>
Output:  
7 19 21 49 
. Sub-Optimal Approach: The brute-force algorithm can be easily improved by just iterating over bitwise subsets. Instead of iterating for every i, we can simply iterate for the bitwise subsets only. Iterating backward for i=(i-1)&x gives us every bitwise subset, where i starts from x and ends at 1. If the mask x has k set bits, we do 2k iterations. A number of k set bits will have 2k bitwise subsets. Therefore total number of mask x with k set bits is. Therefore the total number of iterations is ∑2k = 3n Time Complexity: O(3n)Below is the implementation of above idea:  
C++
Java
Python3
C#
PHP
Javascript
// CPP program for sub-optimal// approach of SumOverSubsets DP#include <bits/stdc++.h>using namespace std; // function to print the sum over subsets valuevoid SumOverSubsets(int a[], int n) {   // array to store the SumOverSubsets  int sos[1 << n] = {0};   // iterate for all possible x  for (int x = 0; x < (1 << n); x++) {    sos[x] = a[0];     // iterate for the bitwise subsets only    for (int i = x; i > 0; i = (i - 1) & x)      sos[x] += a[i];  }   // print all the subsets  for (int i = 0; i < (1 << n); i++)    cout << sos[i] << " ";} // Driver Codeint main() {  int a[] = {7, 12, 14, 16};  int n = 2;  SumOverSubsets(a, n);  return 0;}
// java program for sub-optimal// approach of SumOverSubsets DPpublic class GFG {         // function to print the sum over    // subsets value    static void SumOverSubsets(int a[], int n)    {             // array to store the SumOverSubsets        int sos[] = new int[(1 << n)];                 // iterate for all possible x        for (int x = 0; x < (1 << n); x++) {            sos[x] = a[0];                     // iterate for the bitwise subsets only            for (int i = x; i > 0; i = (i - 1) & x)                sos[x] += a[i];        }                 // print all the subsets        for (int i = 0; i < (1 << n); i++)            System.out.print(sos[i] + " ");    }         // Driver code    public static void main(String args[])    {        int a[] = {7, 12, 14, 16};        int n = 2;                 SumOverSubsets(a, n);    }} // This code is contributed by Sam007
# Python program for sub-optimal# approach of SumOverSubsets DP # function to print sum over subsets valuedef SumOverSubsets(a, n):    sos = [0]*(1 << n)     # iterate for all possible x    for x in range((1 << n)):        sos[x] = a[0]                 # iterate for the bitwise subsets only        i = x         while i > 0:          sos[x] += a[i]          i = ((i - 1) & x)   # print all the subsets    for i in range(1<<n):        print(sos[i], end = " ") # Driver Codeif __name__ == '__main__':    a = [7, 12, 14, 16]    n = 2    SumOverSubsets(a, n) # This code is contributed by mohit kumar 29.
// C# program for sub-optimal// approach of SumOverSubsets DPusing System; class GFG {         // function to print the sum over    // subsets value    static void SumOverSubsets(int []a, int n)    {             // array to store the SumOverSubsets        int []sos = new int[(1 << n)];                 // iterate for all possible x        for (int x = 0; x < (1 << n); x++) {            sos[x] = a[0];                     // iterate for the bitwise subsets only            for (int i = x; i > 0; i = (i - 1) & x)                sos[x] += a[i];        }                 // print all the subsets        for (int i = 0; i < (1 << n); i++)        Console.Write(sos[i] + " ");    }         // Driver code    static void Main()    {        int []a = {7, 12, 14, 16};        int n = 2;                 SumOverSubsets(a, n);    }} // This code is contributed by Sam007.
<?php// PHP program for sub-optimal// approach of SumOverSubsets DP // function to print the// sum over subsets valuefunction SumOverSubsets($a,$n){     // array to store the SumOverSubsets    $sos=array(1 << $n);         // iterate for all possible x    for ($x = 0; $x < (1 << $n); $x++)    {        $sos[$x] = $a[0];             // iterate for the bitwise        // subsets only        for ($i = $x; $i > 0; $i = ($i - 1) & $x)        $sos[$x] += $a[$i];    }         // print all the subsets    for ($i = 0; $i < (1 << $n); $i++)        echo $sos[$i] . " ";} // Driver Code$a = array(7, 12, 14, 16);$n = 2;SumOverSubsets($a, $n); // This code is contributed by Sam007.?>
<script>       // Javascript program for sub-optimal    // approach of SumOverSubsets DP         // function to print the sum over    // subsets value    function SumOverSubsets(a, n)    {              // array to store the SumOverSubsets        let sos = new Array((1 << n));        sos.fill(0);                  // iterate for all possible x        for (let x = 0; x < (1 << n); x++) {            sos[x] = a[0];                      // iterate for the bitwise subsets only            for (let i = x; i > 0; i = (i - 1) & x)                sos[x] += a[i];        }                  // print all the subsets        for (let i = 0; i < (1 << n); i++)            document.write(sos[i] + " ");    }         let a = [7, 12, 14, 16];    let n = 2;     SumOverSubsets(a, n); </script>
Output:  
7 19 21 49 
Time Complexity: O(n*2n) Auxiliary Space: O(n2)Reference: http://home.iitk.ac.in/~gsahil/cs498a/report.pdf 
Sam007
Shivi_Aggarwal
mohit kumar 29
mukesh07
suresh07
surindertarika1234
khushboogoyal499
saurabh1990aror
Bit Algorithms
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
Ordered Set and GNU C++ PBDS
Insert Operation in B-Tree
Binary Indexed Tree or Fenwick Tree
Design a Chess Game
Binomial Heap
Red-Black Tree | Set 3 (Delete)