Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 25, 2018 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/2936a084d55146890ecd56db1efd2a6a to your computer and use it in GitHub Desktop.
Save jianminchen/2936a084d55146890ecd56db1efd2a6a to your computer and use it in GitHub Desktop.
Leetcode 312 - burst balloon - with a bug - the value is 218 instead of 167, need to look into the bug in the code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode312_burstBalloons
{
/// <summary>
/// the code is written by learning from the video
/// https://www.youtube.com/watch?v=Ci39lcoLbyw
///
/// </summary>
class Program
{
static void Main(string[] args)
{
RunTestcase();
}
static public void RunTestcase()
{
var numbers = new int[] { 3, 1, 5, 8 };
Debug.Assert(RunBurstBalloons(numbers) == 167);
}
public static int RunBurstBalloons(int[] numbers)
{
var length = numbers.Length;
var size = length + 2;
var preprocessed = new int[size];
preprocessed[0] = 1;
preprocessed[length + 1] = 1;
for (int i = 0; i < length; i++)
{
preprocessed[i + 1] = numbers[i];
}
var dp = new int[size, size];
for (int i = 0; i + 1 < size; i++)
{
dp[i, i + 1] = preprocessed[i] * preprocessed[i + 1];
}
for (int i = 0; i + 2 < size; i++)
{
dp[i, i + 2] = preprocessed[i] * preprocessed[i + 1] * preprocessed[i + 2];
}
for (int range = 3; range < size; range++)
{
for (int start = 0; start + range < size; start++)
{
// start, end -> calculate dp[start, end]
var end = start + range;
dp[start, end] = calculateMaxByLastBurst(dp, start, end, preprocessed);
}
}
return dp[0, size - 1];
}
private static int calculateMaxByLastBurst(int[,] dp, int start, int end, int[] numbers)
{
var max = int.MinValue;
var startValue = numbers[start];
var endValue = numbers[end];
for (int lastBurst = start + 1; lastBurst < end; lastBurst++)
{
var current = startValue * endValue * numbers[lastBurst];
current += dp[start, lastBurst] + dp[lastBurst, end];
if (current > max)
max = current;
}
return max;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment