LeetCode 2647: Color the Triangle Red Solution

Master LeetCode problem 2647 (Color the Triangle Red), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2647. Color the Triangle Red

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming with a bottom-up approach. We can start from the bottom row of the triangle and then move up row by row, calculating the maximum sum path that ends at each cell. We can update each cell with the sum of the current cell value and the maximum of the two possible parent cells from the row below. Finally, the answer will be the maximum value in the top row.

Here are the step-by-step iterations:

  1. Start from the bottom row and fill it with the given values.
  2. For each cell in the above row, update it to be the sum of the current value and the maximum of the two parent cells from the row below.
  3. Repeat step 2 for each row until we reach the top row.
  4. The answer will be the maximum value in the top row.

Time complexity: O(n^2) where n is the number of rows in the triangle. Space complexity: O(n) for storing the intermediate results in the current row.

: :

Solution Code

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[] dp = new int[n];
        
        for (int i = 0; i < n; i++) {
            dp[i] = triangle.get(n - 1).get(i);
        }
        
        for (int row = n - 2; row >= 0; row--) {
            for (int i = 0; i <= row; i++) {
                dp[i] = triangle.get(row).get(i) + Math.min(dp[i], dp[i + 1]);
            }
        }
        
        return dp[0];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2647 (Color the Triangle Red)?

This page provides optimized solutions for LeetCode problem 2647 (Color the Triangle Red) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2647 (Color the Triangle Red)?

The time complexity for LeetCode 2647 (Color the Triangle Red) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2647 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2647 in Java, C++, or Python.

Back to LeetCode Solutions