Showing posts with label MinimumSubarrayOfSumk. Show all posts
Showing posts with label MinimumSubarrayOfSumk. Show all posts

Sunday, 16 May 2021

Minimum Subarray Of Sumk

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.


Input: target = 7, nums = [2,3,1,2,4,3]
Output:

Explanation: The subarray [4,3] has the minimal length under the problem constraint. 


public class MinimumSubarrayOfSumk {

    public static void main(String[] args) {

        int[] arr = {

                10,5,13,4,8,4,5,11,14,9,16,10,20,8};

        int target  =80;


        int i =-1;

        int j=-1;

        int sum = 0;

        int length = Integer.MAX_VALUE;

        while (true){

        boolean f1 = false,f2 = false;

            while (i<arr.length-1 && sum<target){

                f1 = true;

                i++;

                sum+=arr[i];

                if(sum>=target){

                    length = Math.min(length,i-j);

                    break;

                }

               // f1 = true;

            }


            while (j<i && sum>=target){

                f2 = true;

                j++;

                sum-=arr[j];

                if(sum>=target){

                    length = Math.min(length,i-j);

                }else{

                    break;

                }

               // f2 = true;


            }


            if(!f1 && !f2){

                break;

            }


        }


        System.out.println(length);



    }

}


Result: 6

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...