From 0108a6992c04f8e17fa4e8c5ce5395f977f41cb1 Mon Sep 17 00:00:00 2001 From: Priyanshuischamp Date: Sun, 6 Oct 2024 23:37:34 +0530 Subject: [PATCH] Create PaintersPartition.cpp Added solution code for homework problem (painters partition problem) from your youtube video. --- .../PaintersPartition.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Lecture015 Binary Search Advanced Problems/PaintersPartition.cpp diff --git a/Lecture015 Binary Search Advanced Problems/PaintersPartition.cpp b/Lecture015 Binary Search Advanced Problems/PaintersPartition.cpp new file mode 100644 index 00000000..a6ebf362 --- /dev/null +++ b/Lecture015 Binary Search Advanced Problems/PaintersPartition.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + +bool isPossible(vector &boards, int n, int k, int mid) { + int painterCount = 1; + int boardcount = 0; + + for(int i = 0; i < n; i++) + { + if(boardcount + boards[i] <= mid) + { + boardcount += boards[i]; + } + else + { + painterCount++; + if(painterCount > k || boards[i] > mid) + { + return false; + } + boardcount = boards[i]; //ensures that when a new painter is assigned board, they start with the count of the current board (boards[i]). + } + } + return true; +} + +int findLargestMinDistance(vector &boards, int k) +{ + + // Initialize the binary search range + int s = 0; + int boardsum = 0; + int n= boards.size(); + + for(int i = 0; i < n; i++) + { + boardsum += boards[i]; // Total boardsum of all board + } + + int e = boardsum; // End point: boardsum of all board + int ans = -1; + int mid = s + (e - s) / 2; + + // Binary search to find the minimum number of board + while(s <= e) + { + if(isPossible(boards, n, k, mid)) + { + ans = mid; + e = mid - 1; // Try for a smaller value + } + else + { + s = mid + 1; // Try for a larger value + } + mid = s + (e - s) / 2; + } + + return ans; +} +