Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split Array Largest Sum Problem - Binary Search #126

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Searching/splitArray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/* Problem Statement : Given an integer array nums and an integer k,
split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.
Return the minimized largest sum of the split.
Note - A subarray is a contiguous part of the array.*/


#include<bits/stdc++.h>
using namespace std;
#define ll long long int

int splitArray(vector<int>& nums, int k) {
int l = 0, r = 0, n = nums.size();
for (int i = 0; i < n; ++i) l = max(l, nums[i]), r += nums[i];

int mid = 0, ans = 0;
while (l <= r) {
mid = (l + r) / 2;
int count = 0, tempsum = 0;
for (int i = 0; i < n; ++i) {
if (tempsum + nums[i] <= mid) tempsum += nums[i];
else count++, tempsum = nums[i];
}
count++;

if (count <= k) r = mid - 1, ans = mid;
else l = mid + 1;
}
return ans;
}

int main()
{

#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

int n;
cin >> n;
vector<int> vec(n);
for (int i = 0; i < n; i++)
{
cin >> vec[i];
}
int k;
cin >> k;

cout << splitArray(vec, k) << endl;
return 0;
}