Search results
Jul 19, 2024 · In case of multiple subarrays, return the subarray indexes which come first on moving from left to right. If no such subarray exists return an array consisting of element -1. Examples: Input: arr [] = { 15, 2, 4, 8, 9, 5, 10, 23}, sum = 23. Output: 2 5. Explanation: Sum of elements between indices 2 and 5 is 2 + 4 + 8 + 9 = 23.
- Handles Negative Numbers
Given an unsorted array of integers, find a subarray that...
- Handles Negative Numbers
Jul 22, 2024 · The problem is to find the length of the longest sub-array having sum equal to the given value k. Examples: Input: arr [] = { 10, 5, 2, 7, 1, 9 }, k = 15. Output: 4. Explanation: The sub-array is {5, 2, 7, 1}. Input: arr [] = {-5, 8, -14, 2, 4, 12}, k = -5. Output: 5. Naive Approach: Consider the sum of all the sub-arrays and return the length ...
Jul 22, 2024 · Given an unsorted array of integers, find a subarray that adds to a given number. If there is more than one subarray with the sum of the given number, print any of them. Examples: Input: arr [] = {1, 4, 20, 3, 10, 5}, sum = 33. Output: Sum found between indexes 2 and 4. Explanation: Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33.
- 3 min
Aug 1, 2024 · The problem is to find maximum length of subarray with length equal to sum of elements in that subarray. For example: input_arr = [16, -1, 3, -7, 2, 8, 11, 24] output_arr = [-1, 3, -7, 2, 8] Here output_arr has sum 5 which is equal to its length. The solution I wrote uses idea of prefix sum, where we store the current prefix sum in a hashmap ...
Jul 31, 2024 · When we see that the sum is greater than k , we decrement the sum by the element at left index and increment left . When the sum of the subarray is smaller than k , we add an element at right index to sum and increment right . The time complexity of this approach is O(N). C++
5 days ago · Perform the following steps for i = 0 to n -1: Add arr [i] together to get the total. If total equals K , set maxLen to i+1. Check to see if the sum-K is contained in the hash table. If it’s present, then iterate the respective vector and keep updating the maxLen with the maximum length of the subarray. Insert the current sum into the map.
People also ask
How to find number of continuous subarrays whose sum is same as K?
How do you find a subarray with 0 sum?
How to add elements to a subarray if sum is greater than k?
How do you find the length of the longest sub-array?
1 day ago · If a prefix in a hash map has a sum equal to sum – k , the subarray with the specified sum is discovered. The steps for algorithm are: The steps for algorithm are: Create a hashmap to hold a key-value pair, i.e., key = prefix sum of each prefix and value = its index, and a variable to record the current sum as sum .