JAVA | Prefix Sum | Binary Search
Code\n\nclass Solution {\n    public int[] answerQueries(int[] nums, int[] queries) {\n        int n = nums.length;\n        \n        //sorting the array will 
# Code\n```\nclass Solution {\n    public int[] answerQueries(int[] nums, int[] queries) {\n        int n = nums.length;\n        \n        //sorting the array will provide us with the smallest elements first so that the length of the subarray can be maximized for a particular value of sum\n        Arrays.sort(nums);\n        int ans [] = new int [queries.length];\n        int prefix[] = new int [n+1];\n        \n        //filling the prefix array\n        for(int i = 1; i<n+1; i++){ //prefix[0] = 0; for sum = 0\n            prefix[i] = prefix[i-1]+nums[i-1];\n        }\n        /*Prefix array works like this for sorted array 1,2,4,5\n           index: 0    1   2   3   4     index is equal to the length of subarray\n           value: 0    1   3   7   12    value is equal to the sum of subarray of length index\n        */  \n        //searching and returning the length of subarray required for the sum\n        for(int i = 0; i<queries.length; i++){\n            int val = queries[i];\n            ans[i] = binarySearch(val, prefix);\n        }\n        \n        return ans;\n    }\n\n    public int binarySearch(int val, int [] prefix){\n        int low = 0;\n        int high = prefix.length-1;\n        \n        while(low<=high){\n            int mid = (low+high)/2;\n            if(prefix[mid] == val) return mid;\n            else if(prefix[mid] < val) low = mid+1;\n            else high = mid-1;\n        }\n        //if the exact value is not found in prefix array then we will need to return the closest\n        if(val > prefix[high]) return high; //if the sum in queries is larger then the closest value would be at index high else it would be at index low\n        return low;\n    }\n}\n```
['Array', 'Binary Search', 'Sorting', 'Prefix Sum', 'Java']