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)
>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;
}