From e57a66b7c3031afd929b09aef7c96156ff16150b Mon Sep 17 00:00:00 2001 From: Lucianna Mendonca <121981547+luciannamend@users.noreply.github.com> Date: Tue, 22 Jul 2025 22:04:56 -0400 Subject: [PATCH] Refactor 03_recursive sum (Java) to use int[] for better performance and memory efficiency MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "You’re given an array of numbers. You have to add up all the numbers and return the total." Replaced ArrayList with a primitive int[] in the recursive sum method to improve performance and reduce memory usage. - Faster execution: Avoids boxing/unboxing and uses direct array access. - Lower memory usage: Primitive arrays are lighter than ArrayList with boxed types. - Simpler code: No need for imports or list management for fixed-size data. This version is ideal for static numeric datasets where performance and clarity are priorities. --- 03_recursion/java/04_sum/src/Sum.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/03_recursion/java/04_sum/src/Sum.java b/03_recursion/java/04_sum/src/Sum.java index 0abcb2da..d219578e 100644 --- a/03_recursion/java/04_sum/src/Sum.java +++ b/03_recursion/java/04_sum/src/Sum.java @@ -1,19 +1,15 @@ import java.util.*; public class Sum { - public static int sum(ArrayList num_list, int index) { - - if (num_list.size() == index) { - return 0; - } else { - int num = num_list.get(index); - return num + sum(num_list, index + 1); + public static int sum(int[] arr, int startIndex){ + if (startIndex == arr.length) { + return 0; // Base case: end of array } - + return arr[startIndex] + sum(arr, startIndex + 1); } public static void main(String[] args) { - int total = sum(new ArrayList(Arrays.asList(2, 4, 6)), 0); - System.out.println(total); + int[] numbers = new int[]{ 2, 4, 6}; + System.out.println(sum(numbers, 0)); } }