Skip to main content

Mastering One-Dimensional Dynamic Programming Solutions

Complete Java implementation guide for one-dimensional dynamic programming problems with optimal substructure and overlapping subproblems analysis.

One-dimensional dynamic programming represents a fundamental pattern where problems can be broken down into simpler subproblems that build upon each other sequentially, making it an essential skill for FAANG technical interviews and system design scenarios.

1. Pattern Restatement

Clarifying questions to ask the interviewer:

  1. What is the expected size of the input array? Are we dealing with small arrays (n < 100) or potentially large ones (n > 10^6)?
  2. Can the input array contain negative numbers, and should we handle them appropriately?
  3. What is the desired return format? Should we return just the maximum value, or also the indices of the elements involved?
  4. Are we allowed to mutate the input array during computation, or must we preserve it?
  5. What is the target time complexity for follow-up optimization? O(n) or better?

Restate the pattern or problem type in your own words: The one-dimensional dynamic programming pattern involves solving problems by breaking them down into smaller subproblems and storing the results of these subproblems to avoid redundant computations. In one-dimensional DP, we typically process elements sequentially (like in arrays or sequences), where each element's optimal solution depends on previously computed solutions for earlier elements.

Clarify the signal words and constraint shape that point to it: Signal words include "maximum", "minimum", "count", "sum", "longest", "shortest", and phrases like "find the optimal way to..." or "what's the best value given constraints". The constraint shape often involves linear sequences or arrays where decisions at each position depend on prior positions.

Note any assumptions you are making: I assume that the problem involves a linear sequence or array where each element's optimal solution depends on previous elements. I also assume that the subproblems are independent and overlapping, which makes DP applicable.

Identify whether the pattern is best suited for static, streaming, or online scenarios if relevant: This pattern is primarily suited for static scenarios where all input data is available upfront. It's not ideal for streaming or online scenarios where data arrives continuously, as the solution requires looking ahead or backward in a structured way that isn't naturally supported by streaming models.

2. When to Use This Pattern

Signal words and constraint shapes in a problem statement that indicate this pattern:

  • "Maximum/minimum" subproblems with overlapping substructures
  • "Count ways to..." or "Find all possible..." scenarios
  • Problems where optimal solution contains optimal solutions to subproblems
  • "Dynamic programming" or "DP" explicitly mentioned
  • Sequential decision making with state transitions (like house painting, coin change)
  • Problems involving arrays or sequences where previous elements influence future ones

Why this pattern fits better than the most common alternatives:

  • Unlike greedy approaches, DP handles dependencies between choices by storing optimal solutions to subproblems
  • Compared to brute force recursion, DP avoids exponential time complexity through memoization or tabulation
  • Unlike backtracking, DP provides deterministic optimal solutions rather than exploring all possibilities

Conditions where a variation or related pattern applies instead:

  • If the problem has no overlapping subproblems, greedy or divide-and-conquer may be better
  • For problems with only one optimal path (no branching), greedy might suffice
  • If the problem is about finding a single best value without intermediate state tracking, simple iteration might work
  • For problems requiring real-time updates or streaming data, sliding window or online algorithms may be more appropriate

The core insight that makes this pattern work: Optimal substructure and overlapping subproblems allow us to build solutions incrementally, reusing previously computed results to avoid redundant computation and achieve polynomial time complexity instead of exponential.

3. Approach Evolution

Interview communication script:

"My first instinct is to think about this as a classic dynamic programming problem where we need to make optimal choices at each step. Looking at the constraints, I notice this is asking for a maximum/minimum value over a sequence, which suggests DP. But let me think about the brute force approach first - I could try all possible combinations or sequences, but that would be exponential time O(2^n) because for each element we have two choices: include it or exclude it.

But that's O(2^n) because at each element we have two independent choices, and we're exploring all combinations. That's clearly not acceptable for large inputs.

Let me think about how to optimize this. I notice that if I maintain a running optimal value at each position, I can reduce it to O(n) time. The key insight is that this problem has optimal substructure - the optimal solution for a prefix of the array can be built upon optimal solutions for smaller prefixes.

I'm looking at this as a one-dimensional DP where dp[i] represents the optimal solution up to index i. But I can do even better - since we only need the previous state, I don't need to store the entire DP array. This is a classic case where we can optimize space complexity from O(n) to O(1).

The invariant I'm maintaining is that at each position, I know the maximum/minimum value achievable so far, and I'm building up that optimal solution incrementally."

Brute-force approach and why it is not ideal:

The brute force approach would involve generating all possible subsequences or combinations and computing their values, which results in exponential time complexity O(2^n). For example, if we're looking for maximum sum subarray, trying every possible contiguous subarray would require checking all O(n²) subarrays. This approach is not ideal because:

  • Time complexity grows exponentially with input size
  • Space complexity can also be exponential in some variants
  • It's completely wasteful since we're computing the same subproblems multiple times

Improved approach and the key optimization:

The key optimization is recognizing that this problem has optimal substructure and overlapping subproblems. Instead of recomputing values, we can build up solutions incrementally using the recurrence relation.

For one-dimensional DP problems like maximum subarray sum, we can maintain a running maximum at each position. The key insight is that for any position i, the optimal solution ending at that position depends only on the optimal solution ending at position i-1.

We can optimize space from O(n) to O(1) by only keeping track of the previous state rather than storing all intermediate states.

Final approach with step-by-step reasoning:

  1. State definition: Define dp[i] as the optimal value for the subproblem up to index i
  2. Base case: Initialize dp[0] with appropriate starting value (often 0 or first element)
  3. Transition: For each position, compute dp[i] based on previous optimal solution and current element
  4. Optimization: Since we only need the previous state, use variables instead of arrays to reduce space to O(1)
  5. Final answer: Return the computed optimal value

Important invariants that must hold:

  • At each position i, dp[i] represents the optimal solution for subproblem ending at i
  • The recurrence relation must maintain correctness of optimal substructure property
  • For problems like max subarray, we must ensure that we're not including negative sums that would decrease our optimal value
  • The invariant of optimal substructure must hold: optimal solution for larger problem contains optimal solutions for subproblems

4. Data Structure Choice

For one-dimensional dynamic programming problems, the primary data structure choices are:

1. Array/ArrayList - Primary Choice

  • Used to store computed states for each position in the input sequence
  • Time complexity: O(1) for access and update operations
  • Space complexity: O(n) where n is the input size
  • Why needed: Direct mapping from index to computed value enables bottom-up or top-down DP transitions

2. Variables - Space Optimization

  • For problems where only the previous state is needed (like Fibonacci or house robber)
  • Time complexity: O(1) for access and update operations
  • Space complexity: O(1) - constant space
  • Why needed: When we can compute current state using only the immediately previous state, we avoid storing entire arrays

3. Deque/Stack - For Sliding Window or Monotonic Constraints

  • Used in problems like "max sum of subarray with at most k elements" or when maintaining optimal candidates
  • Time complexity: O(1) amortized for insertion/deletion from ends
  • Space complexity: O(k) where k is the window size or constraint limit
  • Why needed: When we need to maintain a sliding window of valid states or optimal candidates

Helper Structures

  • HashMap for memoization in top-down approaches
  • Priority queues for problems involving optimal selection from multiple states

The key insight is that most 1D DP problems benefit from either simple array storage or constant-space variables, depending on whether the state transition requires only the previous state or the entire history.

5. Algorithm Walkthrough

Let me trace through the algorithm with a concrete example to demonstrate how it works step-by-step.

Example: nums = [1, 2, 3, 1]

Step 1: Initialize dp[0] = nums[0] = 1

  • We can only take the first element, so our maximum loot is 1

Step 2: Compute dp[1] = max(nums[0], nums[1]) = max(1, 2) = 2

  • We can either take house 0 (value 1) or house 1 (value 2)
  • Taking house 1 gives us better value, so dp[1] = 2

Step 3: Compute dp[2] = max(dp[1], dp[0] + nums[2]) = max(2, 1 + 3) = 4

  • Option A: Don't take house 2, keep previous best (dp[1] = 2)
  • Option B: Take house 2, add to best up to house 0 (dp[0] + nums[2] = 1 + 3 = 4)
  • Choose the better option: 4

Step 4: Compute dp[3] = max(dp[2], dp[1] + nums[3]) = max(4, 2 + 1) = 4

  • Option A: Don't take house 3, keep previous best (dp[2] = 4)
  • Option B: Take house 3, add to best up to house 1 (dp[1] + nums[3] = 2 + 1 = 3)
  • Choose the better option: 4

Final Result: dp[3] = 4

The algorithm maintains the key invariant that dp[i] represents the maximum amount we can rob from houses 0 through i, ensuring no adjacent houses are robbed. At each step, we compare two choices: either skip the current house (keeping previous best) or rob it (adding to the best from two steps back). This greedy selection at each position leads to the globally optimal solution.

Edge cases are handled naturally:

  • For empty array, we return 0
  • For single element, we return that element
  • For two elements, we return the maximum of the two

6. Java Solution

public class OneDimensionalDP {
    
    /**
     * Solves the classic House Robber problem using 1D dynamic programming
     * 
     * @param nums array of integers representing money in each house
     * @return maximum amount that can be robbed without alerting police
     */
    public int rob(int[] nums) {
        // Handle edge cases
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        if (nums.length == 1) {
            return nums[0];
        }
        
        // dp[i] represents the maximum money that can be robbed up to house i
        int[] dp = new int[nums.length];
        
        // Base cases
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        
        // Fill the dp array using the recurrence relation:
        // dp[i] = max(dp[i-1], dp[i-2] + nums[i])
        // Either skip current house (take dp[i-1]) or rob current house (dp[i-2] + nums[i])
        for (int i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
        }
        
        return dp[nums.length - 1];
    }
    
    /**
     * Space-optimized version of house robber
     * Uses only two variables instead of full array
     * 
     * @param nums array of integers representing money in each house
     * @return maximum amount that can be robbed without alerting police
     */
    public int robOptimized(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        if (nums.length == 1) {
            return nums[0];
        }
        
        // Only need to track the last two computed values
        int prev2 = nums[0];  // dp[i-2]
        int prev1 = Math.max(nums[0], nums[1]);  // dp[i-1]
        
        for (int i = 2; i < nums.length; i++) {
            int current = Math.max(prev1, prev2 + nums[i]);
            prev2 = prev1;
            prev1 = current;
        }
        
        return prev1;
    }
}

The solution implements the classic House Robber problem using 1D dynamic programming. It uses a bottom-up approach where dp[i] represents the maximum money that can be robbed up to house i. The recurrence relation considers whether to rob the current house or skip it, choosing the option that maximizes profit.

The optimized version reduces space complexity from O(n) to O(1) by only keeping track of the last two computed values, which is sufficient since we only need to reference the previous two states in our recurrence relation.

7. Complexity Analysis

Time Complexity: O(n)

The algorithm makes a single pass through the input array of size n, performing constant-time operations at each step. For each element, we compute the maximum between including and excluding the current element, which takes O(1) time. Since we process each element exactly once, the overall time complexity is linear.

Space Complexity: O(1)

The solution uses only a constant amount of extra space regardless of input size. We maintain just two variables (incl and excl) to track the maximum sums, and a few local variables for temporary storage. No additional data structures like arrays or hash maps are required, making the space complexity constant.

Why These Bounds Are Correct:

The time bound is tight because we must examine each element at least once to determine the optimal solution. The space bound is also tight since we're using only a fixed number of variables and not creating any data structures that scale with input size.

Optimality:

This solution is optimal for the problem as stated. Since we need to consider each element at least once to make a decision about whether to include it in the maximum sum, O(n) time complexity is unavoidable. The constant space usage represents the best possible space efficiency for this problem, as we cannot reduce the state tracking to less than two variables.

The solution achieves the theoretical lower bounds for both time and space complexity, making it near-optimal. The linear time complexity matches the information-theoretic minimum required to process all input elements, and the constant space usage is optimal for maintaining only the necessary state information.

8. Edge Cases & Pitfalls

Empty and Minimal Inputs

  • Empty array: When nums.length == 0, the solution should return appropriate default (e.g., 0 for sum-based problems, or handle as invalid input)
  • Single element: When nums.length == 1, the DP state should handle this base case correctly, typically returning that single element as the answer
  • Two elements: Must ensure both elements are considered in the recurrence relation

Duplicate Values and Repeated States

  • Duplicate numbers: The algorithm should work correctly with duplicates, but care must be taken in state transitions to avoid double-counting or incorrect optimization
  • Repeated subproblems: In some DP problems, identical subproblems may be solved multiple times; memoization or tabulation should prevent redundant computation

Boundary Conditions

  • Negative indices: When using index-based DP, ensure that array bounds are checked to prevent ArrayIndexOutOfBoundsException
  • Large input sizes: For very large arrays (e.g., > 10^5), ensure that space complexity is acceptable and that integer overflow isn't a concern
  • Zero values: When dealing with sums or products, zero values can change the optimal solution and must be handled explicitly

Common Implementation Mistakes

  • Incorrect base case initialization: Forgetting to initialize the first state or setting it incorrectly can lead to wrong answers
  • Off-by-one errors in iteration: When building the DP table, iterating from 0 to n-1 or 1 to n can cause boundary issues
  • Not handling the recurrence relation properly: Failing to correctly express the relationship between current and previous states
  • Using wrong data types: Using int instead of long for accumulating large sums, or not considering overflow in intermediate steps
  • Mutating input array: If the problem requires preserving the original input, ensure that any modifications to the input are not made in-place without proper handling

Example of Common Pitfall

// Incorrect: Not initializing base case properly
int[] dp = new int[n];
// dp[0] is not initialized, leading to unpredictable behavior
// Correct: Proper initialization
int[] dp = new int[n];
dp[0] = nums[0]; // or appropriate base case

9. Alternative Approaches

There are several alternative approaches to solving one-dimensional DP problems, each with their own trade-offs:

Brute Force with Memoization: Instead of building the DP table bottom-up, we could use recursion with memoization. This approach maintains the same time complexity O(n) but uses O(n) space for the call stack and memoization table. The recursive approach might be more intuitive for some but can lead to stack overflow issues with very large inputs.

Space-Optimized Iterative: For problems where we only need the previous state to compute the current state, we can optimize space usage from O(n) to O(1). For example, in classic Fibonacci or house robber problems, we only need dp[i-1] and dp[i-2] to compute dp[i]. This approach trades readability for space efficiency but requires careful indexing management.

Two-Pass Approach: Some problems can be solved with two passes - one forward and one backward. For instance, in the "Product of Array Except Self" problem, we can compute prefix products in one pass and suffix products in another. This approach makes the logic more explicit but doubles the number of iterations.

Sliding Window: When the DP state depends only on a fixed-size window of previous states, we can use sliding window techniques. This is particularly effective for problems like "Maximum Subarray" where the optimal solution can be found by maintaining a window of relevant elements.

The chosen solution is preferred because it provides clean, readable code with optimal time complexity while maintaining a reasonable space complexity that's easy to reason about and debug. The iterative bottom-up approach is generally more intuitive than recursive solutions for most engineers, and the O(n) space complexity is acceptable for most practical applications.

10. Test Cases

public class TestCases {
    public static void main(String[] args) {
        // Test case 1: Basic example from problem description
        int[] nums1 = {1, 2, 3, 1};
        // Expected: 4 (take 1 and 3)
        
        // Test case 2: All elements are the same
        int[] nums2 = {2, 2, 2, 2};
        // Expected: 4 (take first and third)
        
        // Test case 3: Empty array
        int[] nums3 = {};
        // Expected: 0
        
        // Test case 4: Single element
        int[] nums4 = {5};
        // Expected: 5
        
        // Test case 5: Two elements
        int[] nums5 = {1, 2};
        // Expected: 2
        
        // Test case 6: Alternating high/low values
        int[] nums6 = {2, 1, 4, 9};
        // Expected: 11 (take 2 and 9)
        
        // Test case 7: Negative numbers
        int[] nums7 = {-1, -2, 3, -4, 5};
        // Expected: 8 (take 3 and 5)
        
        // Test case 8: Large values
        int[] nums8 = {1000, 1, 1000, 1};
        // Expected: 2000 (take first and third)
    }
}

Sample Test Cases:

  1. Basic Example: [1, 2, 3, 1] → Expected: 4

    • Take elements at indices 0 and 2 (values 1 and 3)
    • Covers the core scenario from problem description
  2. Duplicate Values: [2, 2, 2, 2] → Expected: 4

    • All elements same, optimal is to take alternating elements
    • Tests handling of repeated states
  3. Edge Case - Empty Array: [] → Expected: 0

    • Validates base case handling
    • Tests proper termination
  4. Edge Case - Single Element: [5] → Expected: 5

    • Validates minimal input handling
    • Tests boundary condition
  5. Edge Case - Two Elements: [1, 2] → Expected: 2

    • Tests simple case where optimal is to take the larger element
    • Validates proper comparison logic
  6. Alternating Pattern: [2, 1, 4, 9] → Expected: 11

    • Tests optimal selection when elements aren't simply ordered
    • Validates that we don't just take the maximum element
  7. Negative Numbers: [-1, -2, 3, -4, 5] → Expected: 8

    • Tests handling of negative values in optimal selection
    • Validates that we can include positive numbers even with negatives present
  8. Large Values: [1000, 1, 1000, 1] → Expected: 2000

    • Tests performance with large numbers
    • Validates that our DP approach scales properly

These test cases cover the fundamental scenarios and edge conditions for the House Robber problem, ensuring robustness of the solution across various input patterns.

11. Final Summary

The core idea is to solve the maximum subarray sum problem using dynamic programming by maintaining the maximum sum ending at each position, which elegantly captures the trade-off between extending the current subarray or starting fresh. This solution works because it leverages the optimal substructure property where the best solution at each position depends only on the previous optimal solution, making it both time and space efficient with O(n) time and O(1) space complexity. The key insight is that we can make a locally optimal choice at each step (extend or restart) that leads to a globally optimal solution, demonstrating how dynamic programming can transform a seemingly complex optimization problem into a simple iterative decision process.

Was this article helpful?

Topics in this article

More from DSA Patterns

Stay in the Loop

Get curated DSA patterns, coding problems, frontend and backend LLD/HLD, and AI/ML System Design insights delivered straight to your inbox. No spam, just focused interview and engineering content.