Leetcode 312. poke balloons

topic:

N-balloons, numbered 0 to n-1, each marked with a balloon numbers that exist in the array nums.

Now we ask you to burst all the balloons. Whenever you burst a balloon i, you can get nums [left] * nums [i] * nums [right] coins. Here the left and right and the number i representatives of two adjacent balloons. Note that when you burst the balloon i, balloons left and right balloon becomes adjacent balloon.

Seeking available to the maximum number of coins.

Description:

You can assume nums [-1] = nums [n ] = 1, they are not real but note that it is not be punctured.
0 ≤ n ≤ 500, 0 ≤ nums [i] ≤ 100


Example:

Input: [3,1,5,8]
Output: 167 
explained: nums = [3,1,5,8] -> [3,5,8] -> [3,8] -> [8 ] -> []
  Coins. 1 * * =. 3. 3. 5 *. 5 * + +. 1. 8. 3 * * *. 8. 8 +. 1. 1 * = 167 is

Ideas:

 

Finally, a balloon is punctured, the entire balloon will array divided into two parts.

It can be solved using dynamic programming:

Defined dp [i] [j]: from balloons i to balloon j the maximum score attainable.

Setting a relationship i <k <j, nums [ k] is the last to be punctured balloon.

State transition equation can be obtained:

for( k, k∈(i, j) )   

dp[ i ][ j ] = Math.max(dp[ i ][ j ], nums[ i ] * nums[ k ] * nums[ j ] + dp[ i ][ k ] + dp[ k ][ j ]);

nums [i] * nums [k] * nums [j] + dp [i] [k] + dp [k] [j], for stamp finished k maximum score left + stamp End k maximum score right + stamp End scores of k

. 1  class Solution {
 2      public  int maxCoins ( int [] the nums) {
 . 3          // to add a respective end to the old array of non-burst. 1 
. 4          int [] = n_nums new new  int [nums.length + 2 ];
 . 5          for ( int 0 = I; I <nums.length; ++ I) {
 . 6              n_nums [I +. 1] = the nums [I];
 . 7          }
 . 8          n_nums [0] =. 1 ;
 . 9          n_nums [n_nums.length -. 1] =. 1 ;
 10          
. 11          int [] [] DP = new new  int[n_nums.length] [n_nums.length];
 12 is          
13 is          for ( int j = 2; j <n_nums.length; j ++) { // j∈ [2, n_nums.length), because a large ratio i 2 j at least ; 
14              for ( int I = J - 2; I> = 0; Inc. (www.i-levelmedia.com)) {     // i∈ [0, J - 2] 
15                  for ( int K = J -. 1; K> I; - K) { // k∈ (I, J) 
16                      DP [I] [J] = Math.max (DP [I] [J], n_nums [I] n_nums * [K] * n_nums [J] + DP [I] [K] + DP [K] [j]); // every time the updated i-th to the j th of the maximum score 
. 17                  }
 18 is              }
 . 19          }
 20 is          returnDP [0] [n_nums.length -. 1]; // returns a 0 to the last maximum score 
21      }
 22 }

 

Time complexity (n ^ 3);

Space complexity (n ^ 2);

 

Guess you like

Origin www.cnblogs.com/ledphz/p/11299513.html