Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize number of Knapsacks with total weigh W required to store Array containing elements greater than W/3
Next article icon

Minimize number of Knapsacks with total weigh W required to store Array containing elements greater than W/3

Last Updated : 17 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array, arr[] and weight W. The task is to minimize the number of Knapsacks required to store all elements of the array. A single knapsack can store a maximum total weight of W. 
NOTE: Each integer of the array is greater than (W/3).

Examples:

Input: arr[] = {150, 150, 150, 150, 150},  W = 300
Output: 3
Explanation: Minimum of 3 Knapsacks are required to store all elements
Knapsack 1 - {150, 150}, Knapsack 2 - {150, 150}, Knapsack 3 - {150}. The weight of each knapsack is <= W.

Input: arr[] = {130, 140, 150, 160}, W = 300
Output: 2
Explanation: The knapsacks can be filled as {130, 150}, {140, 160}.

 

Approach: This problem can be solved by using the Two-Pointer approach and Sorting. Follow the steps below to solve the given problem.

  • Sort the array in non-decreasing order.
  • As the array contains elements with values greater than W/3 so no knapsack can contain more than two elements.
  • Maintain two pointers L and R. Initially L = 0, R = N-1.
  • Maintain a while loop for values L <= R.
  • For each L and R check the value arr[L] + A[R] <= W. If this is true then it is possible to put these blocks in the same knapsack. Increment L by 1 and decrease R by 1.
  • Otherwise, the knapsack will have a single element of value arr[i]. Decrease R by 1.
  • Increment answer for each valid step.

Below is the implementation of the above approach: 

C++
// C++ implementation for the above approach #include <bits/stdc++.h> using namespace std;  // Function to calculate // minimum knapsacks required to int minimumKnapsacks(int A[], int N, int W) {     // Variable to store     // the knapsacks required     int ans = 0;      // Maintain two pointers L and R     int L = 0, R = N - 1;      // Sort the array in     // non-decreasing order     sort(A, A + N);      // Maintain a while loop     while (L <= R) {          // Check if there two elements         // can be stored in a         // single knapsack         if (A[L] + A[R] <= W) {              // Increment the answer             ans++;              // Decrease the right pointer             R--;              // Increase the left pointer             L++;         }         else {             // A single knapsack will be required             // to store the Right element             R--;             ans++;         }     }     return ans; }  // Driver Code int main() {     int W = 300;     int arr[] = { 130, 140, 150, 160 };      // To store the size of arr[]     int N = sizeof(arr) / sizeof(arr[0]);      // Print the answer     cout << minimumKnapsacks(arr, N, W); } 
Java
// Java program for the above approach import java.util.*; public class GFG {  // Function to calculate // minimum knapsacks required to static int minimumKnapsacks(int A[], int N, int W) {        // Variable to store     // the knapsacks required     int ans = 0;      // Maintain two pointers L and R     int L = 0, R = N - 1;      // Sort the array in     // non-decreasing order     Arrays.sort(A);      // Maintain a while loop     while (L <= R) {          // Check if there two elements         // can be stored in a         // single knapsack         if (A[L] + A[R] <= W) {              // Increment the answer             ans++;              // Decrease the right pointer             R--;              // Increase the left pointer             L++;         }         else {             // A single knapsack will be required             // to store the Right element             R--;             ans++;         }     }     return ans; }  // Driver code public static void main (String args[]) {        int W = 300;     int arr[] = { 130, 140, 150, 160 };      // To store the size of arr[]     int N = arr.length;      // Print the answer     System.out.println(minimumKnapsacks(arr, N, W)); } }  // This code is contributed by Samim Hossain Mondal. 
Python3
# Python implementation for the above approach  # Function to calculate # minimum knapsacks required to def minimumKnapsacks(A, N, W):     # Variable to store     # the knapsacks required     ans = 0;      # Maintain two pointers L and R     L = 0     R = N - 1;      # Sort the array in     # non-decreasing order     A.sort();      # Maintain a while loop     while (L <= R):          # Check if there two elements         # can be stored in a         # single knapsack         if (A[L] + A[R] <= W):              # Increment the answer             ans += 1              # Decrease the right pointer             R -= 1              # Increase the left pointer             L += 1         else:             # A single knapsack will be required             # to store the Right element             R -= 1             ans += 1     return ans;   # Driver Code  W = 300; arr = [ 130, 140, 150, 160 ]  # To store the size of arr[] N = len(arr);  # Print the answer print(minimumKnapsacks(arr, N, W))  # This code is contributed by saurabh_jaiswal. 
C#
// C# program for the above approach using System; public class GFG {  // Function to calculate // minimum knapsacks required to static int minimumKnapsacks(int []A, int N, int W) {        // Variable to store     // the knapsacks required     int ans = 0;      // Maintain two pointers L and R     int L = 0, R = N - 1;      // Sort the array in     // non-decreasing order     Array.Sort(A);      // Maintain a while loop     while (L <= R) {          // Check if there two elements         // can be stored in a         // single knapsack         if (A[L] + A[R] <= W) {              // Increment the answer             ans++;              // Decrease the right pointer             R--;              // Increase the left pointer             L++;         }         else {             // A single knapsack will be required             // to store the Right element             R--;             ans++;         }     }     return ans; }  // Driver code public static void Main () {        int W = 300;     int []arr = { 130, 140, 150, 160 };      // To store the size of arr[]     int N = arr.Length;      // Print the answer     Console.Write(minimumKnapsacks(arr, N, W)); } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
<script>     // JavaScript implementation for the above approach      // Function to calculate     // minimum knapsacks required to     const minimumKnapsacks = (A, N, W) => {              // Variable to store         // the knapsacks required         let ans = 0;          // Maintain two pointers L and R         let L = 0, R = N - 1;          // Sort the array in         // non-decreasing order         A.sort();          // Maintain a while loop         while (L <= R) {              // Check if there two elements             // can be stored in a             // single knapsack             if (A[L] + A[R] <= W) {                  // Increment the answer                 ans++;                  // Decrease the right pointer                 R--;                  // Increase the left pointer                 L++;             }             else              {                              // A single knapsack will be required                 // to store the Right element                 R--;                 ans++;             }         }         return ans;     }      // Driver Code     let W = 300;     let arr = [130, 140, 150, 160];      // To store the size of arr[]     let N = arr.length;      // Print the answer     document.write(minimumKnapsacks(arr, N, W));      // This code is contributed by rakeshsahni  </script> 

Output
2

Time Complexity: O(N*log(N)) 
Auxiliary Space: O(1)


Next Article
Minimize number of Knapsacks with total weigh W required to store Array containing elements greater than W/3

K

kartikmodi
Improve
Article Tags :
  • Greedy
  • Sorting
  • Combinatorial
  • DSA
  • Arrays
  • Quick Sort
  • knapsack
Practice Tags :
  • Arrays
  • Combinatorial
  • Greedy
  • Sorting

Similar Reads

    Minimize cost for reducing array by replacing two elements with sum at most K times for any index
    Given an array arr[] of size N and an integer K. The task is to find the minimum cost required to collect the sum of the array. The sum of the array is collected by picking any element and adding it to an element of any index in the array. The addition of elements at the same index is allowed for at
    11 min read
    Maximize profit by picking elements of different types with total weight K
    Given an array item[] representing type, weight, and profit of N items, the task is to maximize the profit by picking different types of elements (i.e., no two elements are of the same type) such that the total weight is at most pick atmost K. Examples: Input: item[] = [[1, 3, 13], [5, 1, 10], [2, 2
    11 min read
    Minimize the sum after choosing elements from the given three arrays
    Given three arrays A[], B[] and C[] of same size N. The task is to minimize the sum after choosing N elements from these array such that at every index i an element from any one of the array A[i], B[i] or C[i] can be chosen and no two consecutive elements can be chosen from the same array.Examples:
    15+ min read
    Minimum count of elements to be inserted in Array to form all values in [1, K] using subset sum
    Given a sorted array arr[] consisting of N integers, and an integer K, the task is to find the minimum number of elements to be inserted in the array such that any value in the range [1, K] can be formed by adding elements of any subset of the modified array. Examples: Input: arr[] = {1, 3}, K = 6Ou
    7 min read
    Rearrange the given array to minimize the indices with prefix sum at least arr[i]
    Given an array arr[] consisting of N positive integers, rearrange the array to minimize the number of indices i such that the prefix sum from index 1 to index i-1 is greater than or equal to the current element arr[i] i.e. arr[1]+arr[2]+...+arr[i-1] >= arr[i]. Examples: Input: arr[] = [4, 2, 1]Ou
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences