![]() ![]() Check if curr_sum is greater than the target sum.Traverse the array arr from the second element to the last element with a loop variable i ranging from 1 to n-1, where n is the length of the array.Initialize two variables, start and curr_sum, to the first element of the array, i.e., arr.If no sub-array with the sum is found, a message indicating the absence of such a sub-array is printed. If the current sum matches the target sum, the indices of the sub-array are printed. The window, represented by the variables ‘start’ and ‘i’, is moved from the left to the right of the array while maintaining a running sum ‘curr_sum’. ![]() Sliding Window approach:The code uses a sliding window approach to search for a sub-array with a given sum.If no sub-array is found, print “No sub-array found”.If curr_sum is greater than the target sum or j is equal to n-1, break out of the loop and continue with the next element i.If curr_sum is equal to the target sum, print the starting and ending indices of the sub-array as “Subarray found between indexes i and j” and return.Traverse the array arr from i+1 to n with a loop variable j ranging from i+1 to n-1.Traverse the array arr from the first element to the last element with a loop variable i ranging from 0 to n-1, where n is the length of the array.Take the input array arr and target sum sum as input.If no -with the sum is found, it prints a message indicating the absence of such a sub-array. If the sum matches the given sum, it prints the indices of the sub-array and returns. For each starting index ‘i’, it checks all sub-arrays starting from ‘i’ and ending at ‘j’, and calculates their sum. Naive approach: The naive approach to find a sub-array with a given sum in Java involves using a nested loop to check all possible sub-arrays of the given array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |