Posts

Showing posts with the label subarray

1457. Search Subarray

Given an array  arr  and a nonnegative integer  k , you need to find a continuous array from this array so that the sum of this array is  k . Output the length of this array. If there are multiple such substrings, the return end position is the smallest, and if there are more than one, the return start position is the smallest. If no such subarray is found,  -1  is returned. The length of the array does not exceed  10^6 1 0 ​ 6 ​ ​ , each number in the array is less than or equal to  10^6 1 0 ​ 6 ​ ​ , and  k does not exceed  10^6 1 0 ​ 6 ​ ​ . Have you met this question in a real interview?    Yes Problem Correction Example Example 1 : Input:arr=[1,2,3,4,5] ,k=5 Output:2 Explanation: In this array, the earliest contiguous substring is [2,3]. Example 2 : Input:arr=[3,5,7,10,2] ,k=12 Output:2 Explanation: In this array, the earliest consecutive concatenated substrings with a sum of 12 are [5,...

620. Maximum Subarray IV

Given an integer arrays, find a contiguous subarray which has the largest sum and length should be greater or equal to given length  k . Return the largest sum, return 0 if there are fewer than k elements in the array. Ensure that the result is an integer type. k  >  0 Have you met this question in a real interview?    Yes Problem Correction Example Example 1: Input: [-2,2,-3,4,-1,2,1,-5,3] 5 Output: 5 Explanation: [2,-3,4,-1,2,1] sum=5 Example 2: Input: [5,-10,4] 2 Output: -1 Code ( Language :C++) Edit class Solution { public : /** * @param nums: an array of integer * @param k: an integer * @return: the largest sum */ int maxSubarray4 ( vector < int > &nums, int k) { // write your code here const int size = nums.size(); if (size < k){ return 0 ; } vector < int > prefixSum(size + 1 , 0 ); ...