|
| 1 | +//* |
| 2 | +// 2875. Minimum Size Subarray in Infinite Array |
| 3 | +// Medium |
| 4 | +// You are given a 0-indexed array nums and an integer target. |
| 5 | +// A 0-indexed array infinite_nums is generated by infinitely appending the elements of nums to itself. |
| 6 | +// Return the length of the shortest subarray of the array infinite_nums with a sum equal to target. If there is no such subarray return -1. |
| 7 | +// Example 1: |
| 8 | +// Input: nums = [1,2,3], target = 5 |
| 9 | +// Output: 2 |
| 10 | +// Explanation: In this example infinite_nums = [1,2,3,1,2,3,1,2,...]. |
| 11 | +// The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. |
| 12 | +// It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. |
| 13 | +// Example 2: |
| 14 | +// Input: nums = [1,1,1,2,3], target = 4 |
| 15 | +// Output: 2 |
| 16 | +// Explanation: In this example infinite_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. |
| 17 | +// The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. |
| 18 | +// It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. |
| 19 | +// Example 3: |
| 20 | +// Input: nums = [2,4,6,8], target = 3 |
| 21 | +// Output: -1 |
| 22 | +// Explanation: In this example infinite_nums = [2,4,6,8,2,4,6,8,...]. |
| 23 | +// It can be proven that there is no subarray with sum equal to target = 3. |
| 24 | + |
| 25 | +// Constraints: |
| 26 | +// 1 <= nums.length <= 105 |
| 27 | +// 1 <= nums[i] <= 105 |
| 28 | +// 1 <= target <= 109 |
| 29 | +*// |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +class Solution { |
| 34 | + public int minSizeSubarray(int[] nums, int target) { |
| 35 | + //Lets Play with Sliding Window ::: |
| 36 | + //TC : O(n) |
| 37 | + //SC :O(1) |
| 38 | + int sum=0; |
| 39 | + for(int ele:nums){ |
| 40 | + sum+=ele; |
| 41 | + } |
| 42 | + int mul =target/sum; |
| 43 | + target =target%sum; |
| 44 | + int recArr[] = new int[nums.length*2]; |
| 45 | + for(int i=0;i<nums.length;i++){ |
| 46 | + recArr[i] =nums[i]; |
| 47 | + recArr[nums.length+i] =nums[i]; |
| 48 | + } |
| 49 | + int ans=Integer.MAX_VALUE; |
| 50 | + sum=0; |
| 51 | + int start=0,end=0; |
| 52 | + while(end<recArr.length){ |
| 53 | + sum+=recArr[end]; |
| 54 | + while(sum>target && start<=end){ |
| 55 | + sum-=recArr[start]; |
| 56 | + start++; |
| 57 | + } |
| 58 | + if(sum==target){ |
| 59 | + ans=Math.min(ans,end-start+1); |
| 60 | + } |
| 61 | + end++; |
| 62 | + } |
| 63 | + return ans==Integer.MAX_VALUE?-1:ans+(mul*nums.length); |
| 64 | + |
| 65 | + } |
| 66 | +} |
0 commit comments