Created
July 11, 2021 06:55
-
-
Save kshitijvarshne1/a8afa9c0edefdea1196cd0213dc9adca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Created by IntelliJ IDEA. | |
* Author: Kshitij Varshney (kshitijvarshne1) | |
* Date: 01-Jul-21 | |
* Time: 11:36 PM | |
* File: Practice.java | |
*/ | |
public class Practice { | |
public static void main(String[] args) { | |
int[] a = {7, 2, 5, 10, 8}; | |
System.out.println(cookieDist(a, 2)); | |
} | |
static boolean isValid(int[] a, int n, int mid, int k) { | |
int cokkie = 1; | |
int sum = 0; | |
for (int i = 0; i < n; i++) { | |
sum += a[i]; | |
if (sum > mid) { | |
cokkie++; | |
sum = a[i]; | |
} | |
if (cokkie > k) { | |
return false; | |
} | |
} | |
return true; | |
} | |
static int cookieDist(int[] a, int k) { | |
int n = a.length; | |
if (n < k) { | |
return -1; | |
} | |
int sum = 0; | |
int maxi = -1; | |
for (int i = 0; i < n; i++) { | |
maxi = Math.max(maxi, a[i]); | |
sum += a[i]; | |
} | |
int s = maxi; | |
int e = sum; | |
int res = -1; | |
while (s <= e) { | |
int mid = s + (e - s) / 2; | |
if (isValid(a, n, mid, k) == true) { | |
res = mid; | |
e = mid - 1; | |
} else { | |
s = mid + 1; | |
} | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment