How to find maximum of each subarray of some fixed given length in a given array

后端 未结 6 1805
天涯浪人
天涯浪人 2021-02-14 16:41

We are given an array of n elements and an integer k. Suppose that we want to slide a window of length k across the array, reporting the largest value contained in each window.

6条回答
  •  误落风尘
    2021-02-14 17:15

    Please review my code. According to me I think the Time Complexity for this algorithm is

    O(l) + O(n)

        for (int i = 0; i< l;i++){
            oldHighest += arraylist[i];
        }
        int kr = FindMaxSumSubArray(arraylist, startIndex, lastIndex);
    
    
    
        public static int FindMaxSumSubArray(int[] arraylist, int startIndex, int lastIndex){
    
        int k = (startIndex + lastIndex)/2;
        k = k - startIndex;
        lastIndex = lastIndex  - startIndex;
    
        if(arraylist.length == 1){
            if(lcount= oldHighest){
                    oldHighest = highestSum;
                    result = count - l + 1;
                }
                highestSum = 0;
                highestSum += arraylist[0];
                lcount = 1;
            }
            count++;
            return result;
        }
    
        FindMaxSumSubArray(Arrays.copyOfRange(arraylist, 0, k+1), 0, k);
        FindMaxSumSubArray(Arrays.copyOfRange(arraylist, k+1, lastIndex+1), k+1, lastIndex);
    
        return result;
     }
    

    I don't understand if this is better off to do in recursion or just linearly?

提交回复
热议问题