题目:
分四种情况;当left不存在或者不能射击时,得分为 score[i] * score[right];当右边不存在是score[i]*score[left];第三种左右都存在时!
score不是有序的,反正核心是找三个相邻的靶
(这个==)!
与 leetcode312Burst Balloons,略有区别(= = !时间不够)
C++ 以前写的copy过来
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
nums.insert(nums.begin(), 1);
nums.insert(nums.end(), 1);
vector<vector<int> > dp(n + 2, vector<int>(n + 2, 0));
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n - k + 1; i++) {
int j = i + k - 1;
for (int x = i; x <= j; x++) {
int temp = dp[i][x - 1] + nums[i - 1] * nums[x] * nums[j + 1] + dp[x + 1][j];
if (dp[i][j] < temp)
dp[i][j] = temp;
}
}
}
return dp[1][n];
}
};
类似求最大上升子系列 系列有四种情况;
DP问题 区间DP,算法导论动态规划那一章 最烦== (DP用C++还好,说好的用什么语言都行的不是么==)
有更好的思路:优先队列,除去首尾全入队,每次选取score[i]最小值打,直到对空,剩下两个先打小的后打大的,不用在意大的,因为只要不打掉他还会重复利用每次选最小的打,边缘另算
*/
import java.util.Scanner;
public class Demo
{ static int maxScore(int[] score) //分四种情况
int total = 0;
if (score.length <= 1) ////数组长度为0的时候 & 不存在左边和右边的时候边界
{
return total;
}
for (int i = 0; i < score.length; i++)
{ if (score[i] == 0)
{ //分数为0的时候 continue; }
else { if (i == 0)
{ //左边不存在的时候 total += score[i] * score[i + 1]; }
else if (i == score.length - 1)
{ //右边不存在的时候 total += score[i] * score[0]; }
else { total += score[i - 1] * score[i] * score[i + 1]; } } }
return total; }
public static void main(String[] args) {
Scanner in = new Scanner(System.in );
int res;
int _score_size = 0; //数组大小
_score_size = Integer.parseInt(in.nextLine().trim());
int[] _score = new int[_score_size];
int _score_item;
for (int _score_i = 0; _score_i < _score_size; _score_i++)
{ _score_item = Integer.parseInt(in.nextLine().trim());
_score[_score_i] = _score_item; }
res = maxScore(_score);
System.out.println(String.valueOf(res)); } }
,