Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

maxSum

Language/Type: Java recursion recursive backtracking
Author: Marty Stepp (on 2012/11/19)

Write a recursive method maxSum that accepts a list of integers L and an integer limit n as its parameters and uses backtracking to find the maximum sum that can be generated by adding elements of L that does not exceed n. For example, if you are given the list of integers [7, 30, 8, 22, 6, 1, 14] and the limit of 19, the maximum sum that can be generated that does not exceed is 16, achieved by adding 7, 8, and 1. If the list L is empty, or if the limit is not a positive integer, or all of L's values exceed the limit, return 0.

Each index's element in the list can be added to the sum only once, but the same number value might occur more than once in a list, in which case each occurrence might be added to the sum. For example, if the list is [6, 2, 1] you may use up to one 6 in the sum, but if the list is [6, 2, 6, 1] you may use up to two sixes.

Here are several example calls to your method and their expected return values:

List L Limit n maxSum(L, n) returns
[7, 30, 8, 22, 6, 1, 14] 19 16
[5, 30, 15, 13, 8] 42 41
[30, 15, 20] 40 35
[6, 2, 6, 9, 1] 30 24
[11, 5, 3, 7, 2] 14 14
[10, 20, 30] 7 0
[10, 20, 30] 20 20
[] 10 0

You may assume that all values in the list are non-negative. Your method may alter the contents of the list L as it executes, but L should be restored to its original state before your method returns. Do not use any loops in solving this problem.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.