You know a shop where you can buy chocolates for your friend. The shop has limited availablility of chocolates. On day i, there are only Ai chocolates available in the shop. Your friend is angry with you and she asks you to buy her X chocolate otherwise she won't talk to you. Also due to COVID 19 pandemic, the government has imposed lockdown from Lth day to Rth day which means the shop will be closed from L to R (both inclusive). Now you want to find out the no of days she won't talk to you. If you fail to buy her X chocolate on or before nth day, she will never talk to you and print -1 in this case.
Example:
Input: n=5, arrA[] = { 4, 3, 6, 2, 8 }, l=2, r=3, x=3
Output: 1
Approach
Java
public class WhenWillSheTalk {public static void main(String args[]) {int n = 5;long[] arr = new long[n + 1];long arrA[] = { 4, 3, 6, 2, 8 };arr[0] = 0;for (int i = 1; i <= n; i++) {arr[i] = arr[i - 1] + arrA[i - 1];}int q = 1;int l = 2;int r = 3;long x = 3;int day = findDay(arr, l, r, x);System.out.println(day);}static int findDay(long[] arr, int l, int r, long x) {if (x == 0) {return 0;}int result = 0;if (x <= arr[l - 1]) {result = binarySearch(arr, x);} else {long diff = arr[r] - arr[l - 1];result = binarySearch(arr, x + diff);}if (result == arr.length) {result = -1;}while (result > 0 && arr[result - 1] == arr[result]) {result--;}return result;}static int binarySearch(long[] arr, long key) {int start = 1;int end = arr.length - 1;while (start <= end) {int mid = (start + end) / 2;if (arr[mid] == key) {return mid;} else if (arr[mid] < key) {start = mid + 1;} else {end = mid - 1;}}return start;}}
No comments:
Post a Comment