Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace two numbers with a their sum in not more than K in a list

I need help with solving this task.
Given an integer array inputList and integer max. I want to create an array where every two neighboring elements are replaced by their sum if the sum of these elements is not more than max. If there are no such pairs, then output the original list. We need to go through the array once.

List<int> replacedList(int max, List<int> inputList) {
  List<int> outputList = [];
  ...
  return outputList;
}

void main() {
  replacedList(5, [5, 1, 3, 3, 4]);
  replacedList(6, [2, 3, 1, 5, 4, 3]);
}

The output list in the first example will be [5, 4, 3, 4], because only one pair (1+3 <= max which is 5) sutisfied the condition. In the second one will be [5, 6, 4, 3] (there are two pairs: 2 and 3, and 1 and 5)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If I understand correctly what is required, here is the solution

void main() {
  List<int> result = replacedList(6, [2, 3, 1, 5, 4, 3]);
  print(result);
}

List<int> replacedList(int max, List<int> inputList) {
  List<int> outputList = List.from(inputList);
  for (int i = 0; i < outputList.length - 1; i++) {
    if (outputList[i] + outputList[i + 1] <= max) {
      outputList[i] = outputList[i] + outputList[i + 1];
      outputList.removeAt(i + 1);
      if (i > 0) {
        i--;
      }
    }
  }
  return outputList;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading