Sum the consecutive values of an array T if they are less than or equal to a k value

Jose Pablo
2 min readFeb 12, 2021

Image from internet

Sometimes just for fun or with the intention to practice some logic, and algorithm building I solve some algorithm challenges of different levels of complexity. In this case I solved a simple one, the problem description is as follows:

Given an array T of n positive integers and a positive integer value k, sum and copy the values of T into a new array R such that the sums of consecutive entries in T are less than or equal to the value of k. If an entry of T by itself is greater than or equal to k, it is simply copy into R.

For example:

T = [3, 2, 7, 4, 5, 2, 8, 1, 3, 2, 6] and k = 7

The result should be R = [3+2, 7, 4, 5+2, 8, 1+3+2, 6] = [5, 7, 4, 7, 8, 6, 6].

Step by step solution:

  1. Copy the first element of T in the first position of R.
  2. Mark the first position of R as the active position.
  3. For each of the elements in T (from the second position) do as follows:

a. If the sum of the element in T plus R’s active position is less than or equal to k then add this element of T to the R’s active position.

b. If the sentence above is false then move active position to next position in R and copy on it the element in T that could not been added.

4. Repeat step 3 for each of the elements in T.

Java solution:

public int[] sumElementsOfArray(int[] arrayT, int k) {
int arrayR[] = new int[arrayT.length];

int activeRPosition = 0;
arrayR[activeRPosition] = arrayT[activeRPosition];

for (int i = 1; i < arrayT.length; i++) {
if (arrayR[activeRPosition] + arrayT[i] <= k) {
arrayR[activeRPosition] = arrayR[activeRPosition] + arrayT[i];
} else {
activeRPosition++;
arrayR[activeRPosition] = arrayT[i];
}
}

return arrayR;
}

If we execute the previous code with the entrance of the problem description we would get this result:

[3, 2, 7, 4, 5, 2, 8, 1, 3, 2, 6]
[5, 7, 4, 7, 8, 6, 6, 0, 0, 0, 0]

There are zeros at the end of the array due the size of R is the same of T, so the empty fields are filled with zeros.

All the code can be found here.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jose Pablo
Jose Pablo

Written by Jose Pablo

Full time Sr. software engineer and part time MSc in Computer Science student with interest in AI, DL, HPC, and computer graphics. Love outdoors. Foodie.

No responses yet

Write a response