阿里2017年秋招编程题

题目:

分四种情况;当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));   } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值