Largest adjacent sum of size K Algo

By   Tewodros   Date Posted: Sep. 28, 2021  Hits: 1,179   Category:  Algorithm   Total Comment: 0             A+ A-


side

 

Given a list of integers and a target number K, we would like to find the largest adjacent sum of size K.

Examples:

{1,12,-5,-6,50,3};   K= 4 

Ans = 51.  since Maximum sum is (12-5-6+50)

{ 1,-1,2,4,1,-8,10,9};  K=2

Ans = 19 since {10,9} are the only two adjacent number which gives us the maximum sum

{ 1,-1,2,4,10,-8,10,9};  K=3

Ans = 16 since {2,4,10} are the only three adjacent number which gives us the maximum sum

 

Solution:

we first add the first k numbers and then we will try to compare the sum with  sum + nums[i] - nums[i - k] where i = k, k+1, k+2… nums.Length

Basically this means we temporarily assume the sum of the first k number is the best sum but we need to reevaluate our assumption as we navigate through the array one element at a time by forgetting our trailing number (forget the past) and adding the next number in the loop (grasp the future)

 

           double sum = 0;

           for (int i = 0; i < k; i++)

               sum += nums[i];

           double res = sum;

           for (int i = k; i < nums.Length; i++)

           {

               sum += nums[i] - nums[i - k];

               res = Math.Max(res, sum);

           }

           return res;

      


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* pbpwnx

Back to Top