eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

The Rod Cutting Problem is a classic optimization problem that involves finding the best way to cut a rod into pieces to maximize the total revenue.

In this tutorial, we’ll understand the Rod Cutting Problem and explore various approaches to solving it in Java.

2. Understanding the Problem

Imagine we’ve got a rod of length n. We’ve got the flexibility to cut this rod into various lengths and sell those cut segments. Furthermore, we possess a table of prices for different lengths of cut rods. Our goal is to maximize the total revenue.

For example, consider a rod of length n=4 with prices Pi = [1,5,8,9]. The Pi array denotes the price of a rod piece of length i. It means:

P1 = 1 shows the price of a rod piece of length 1 is 1 unit.

P2 = 5 shows the price of a rod piece of length 2 is 5 units.

Similarly, P3 = 8 shows the price of a rod piece of length 3 is 8 units, and

P4 = 9 shows the price of a rod piece of length 4 is 9 units.

We can make various cuts to the rod, and each cut will result in a certain revenue based on the prices of the rod pieces. Here are the possible cuts for a rod of length 4:

  • Cut into 4 pieces of length 1m each [1,1,1,1], resulted in revenue = 1+1+1+1 = $4
  • Cut into 2 pieces of length 2m each [2,2], resulted in revenue = 5+5 = $10
  • Cut into 1 piece of length 4m, resulted in revenue = $9
  • Cut into 3 pieces of length 1m and 2m [1,1,2], resulted in revenue = 1+1+5 = $7
  • Cut into 3 pieces of length 1m and 2m [1,2,1], resulted in revenue = 1+5+1 = $7
  • Cut into 3 pieces of length 1m and 2m [2,1,1], resulted in revenue= 5+1+1 = $7

Here, we can see that by cutting our rod into 2 pieces of length 2m each, we get a total price of $10. Every other combination gives a lower price, so we can see that this is the optimal answer.

3. Recursive Solution

The recursive solution involves decomposing the problem into subproblems and solving them recursively. The recurrence relation used to calculate the maximum revenue for a rod of length n is Rn = max1<=i<=n(Pi+Rn-i).

In the above relation, Rn represents the maximum revenue for a rod of length n, and Pi is the price of a rod piece of length i. Let’s implement the recursive solution:

int usingRecursion(int[] prices, int n) {
    if (n <= 0) {
        return 0;
    }
    int maxRevenue = Integer.MIN_VALUE;
    for (int i = 1; i <= n; i++) {
        maxRevenue = Math.max(maxRevenue, prices[i - 1] + usingRecursion(prices, n - i));
    }
    return maxRevenue;
}

In our example, we check the base case to determine if the rod’s length is equal to or less than 0, resulting in a revenue of 0. We systematically explore all potential cuts using recursion to calculate the maximum revenue for each cut. The result is the highest revenue achieved among all the cuts.

Now, let’s test this approach:

@Test
void givenARod_whenUsingRecursion_thenFindMaxRevenue() {
    int[] prices = {1, 5, 8, 9};
    int rodLength = 4;
    int maxRevenue = RodCuttingProblem.usingRecursion(prices, rodLength);
    assertEquals(10, maxRevenue);
}

The recursive approach works and is relatively easy to understand. However, its exponential time complexity O(2n) makes it impractical for larger instances, as recursive calls will rapidly increase. So, if we’ve got a 4m rod, this approach will take 24 = 16 iterations.

This solution doesn’t directly store the state in a separate data structure like an array or a map. However, it utilizes the call stack provided by the language to keep track of function classes and their respective parameters and local variables.

The lack of memorization in this approach results in redundant computations, as identical subproblems are solved multiple times during the recursive exploration. This inefficiency becomes a significant concern for realistic scenarios with rods of considerable lengths. Recursive solutions can also lead to stack overflow errors if the recursion depth is too large.

4. Memoized Recursive Solution

We can improve our recursive solution by the use of memoization. In this approach, we’ll use a memoization table to store and reuse the results of previously solved subproblems:

int usingMemoizedRecursion(int[] prices, int n) {
    int[] memo = new int[n + 1];
    Arrays.fill(memo, -1);

    return memoizedHelper(prices, n, memo);
}

int memoizedHelper(int[] prices, int n, int[] memo) {
    if (n <= 0) {
        return 0;
    }

    if (memo[n] != -1) {
        return memo[n];
    }
    int maxRevenue = Integer.MIN_VALUE;

    for (int i = 1; i <= n; i++) {
        maxRevenue = Math.max(maxRevenue, prices[i - 1] + memoizedHelper(prices, n - i, memo));
    }

    memo[n] = maxRevenue;
    return maxRevenue;
}

The idea is to avoid redundant computations by checking whether a subproblem has already been solved before solving it again. Our memoization table takes the form of an array, where each index corresponds to the rod length, and the associated value holds the maximum revenue for that specific length.

Now, let’s test this approach:

@Test 
void givenARod_whenUsingMemoizedRecursion_thenFindMaxRevenue() {
    int[] prices = {1, 5, 8, 9};
    int rodLength = 4;
    int maxRevenue = RodCuttingProblem.usingMemoizedRecursion(prices, rodLength);
    assertEquals(10, maxRevenue);
}

By avoiding the redundant calculations through memoization, the time complexity is significantly reduced compared to the naive recursive solution. Now, the time complexity is determined by the number of unique subproblems solved, and for the Rod Cutting problem, it is often O(n2) due to the two nested loops.

This means for a rod of length 10m, we’ll have a time complexity of 100 here, compared to 1024 before, because we’re doing notably less work due to the trimming of nodes. However, this comes at a cost in space complexity. The algorithm must store up to one value for each rod length, giving it a space complexity of O(n).

5. Dynamic Programming Solution

Another approach to solving this problem is via dynamic programming. Dynamic programming solves a problem by dividing it into smaller subproblems. This is very similar to the divide-and-conquer algorithm-solving technique. The major difference, however, is that dynamic programming solves a subproblem only once.

5.1. Iterative (Bottom-Up) Approach

In this approach, avoiding recursion and using an iterative process eliminates the function call overhead associated with the recursive solutions, contributing to enhanced performance:

int usingDynamicProgramming(int[] prices, int n) {
    int[] dp = new int[n + 1];
    for (int i = 1; i <= n; i++) {
        int maxRevenue = Integer.MIN_VALUE;

        for (int j = 1; j <= i; j++) {
            maxRevenue = Math.max(maxRevenue, prices[j - 1] + dp[i - j]);
        }
        dp[i] = maxRevenue;
    }
    return dp[n];
}

Let’s test this approach as well:

@Test 
void givenARod_whenUsingDynamicProgramming_thenFindMaxRevenue() {
    int[] prices = {1, 5, 8, 9};
    int rodLength = 4;
    int maxRevenue = RodCuttingProblem.usingDynamicProgramming(prices, rodLength);
    assertEquals(10, maxRevenue);
}

Our dynamic programming table, represented by the dp array, stores the optimal solutions for each subproblem, where the index i corresponds to the rod length, and dp[i] holds the maximum revenue. The final entry in the dp array, dp[n], contains the maximum revenue for the original problem of a rod with length n.

This approach is also memory-efficient as it doesn’t require an additional memoization table.

5.2. Unbounded Knapsack Solution

The unbounded knapsack approach is a dynamic programming technique used to solve optimization problems where an item can be chosen unlimited times. This means that the same cut length can be selected and included in the rod multiple times if it contributes to maximizing the revenue. Let’s take a look at the implementation:

int usingUnboundedKnapsack(int[] prices, int n) {
    int[] dp = new int[n + 1];

    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < prices.length; j++) {
            if (j + 1 <= i) {
                dp[i] = Math.max(dp[i], dp[i - (j + 1)] + prices[j]);
            }
        }
    }

    return dp[n];
}

Similar to the iterative (bottom-up) approach, this algorithm computes the maximum revenue for each rod length. Let’s test this approach:

@Test 
void givenARod_whenUsingGreedy_thenFindMaxRevenue() {
    int[] prices = {1, 5, 8, 9};
    int rodLength = 4;
    int maxRevenue = RodCuttingProblem.usingUnboundedKnapsack(prices, rodLength);
    assertEquals(10, maxRevenue);
}

The drawback of this approach is the potential for increased space complexity.

6. Conclusion

In this tutorial, we’ve understood the Rod Cutting Problem and discussed various ways to solve it.

The recursive approach offers simplicity but suffers from exponential time complexity. The memoization method addresses this by reusing solutions and introducing slight space complexity. The iterative approach further improves efficiency, eliminating recursion overhead.

The choice between these approaches depends on specific problem characteristics, involving trade-offs in time, space, and implementation complexity.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
3 Comments
Oldest
Newest
Inline Feedbacks
View all comments