zoukankan      html  css  js  c++  java
  • Weekly Contest 129--1021. Best Sightseeing Pair--Medium

    Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them.

    The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them.

    Return the maximum score of a pair of sightseeing spots.

    Example 1:

    Input: [8,1,5,2,6]
    Output: 11
    Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11

    Note:

    2 <= A.length <= 50000
    1 <= A[i] <= 1000

    1.思考

    • 又是一开始就想到用暴力搜索,后来仔细一想就觉得不对;
    • 然后开始研究A[i] + A[j] + i - j这个算是算式,就想到用A1、A2两个vector来分别存放A[i]+i、A[i]-i;
    • 接着计算A1[i]+max(A2[i+1...len]),因为要一直用到max_element()这个函数,所以干脆就提前算好,A2[i]为从i到len-1的A2中最大的数;
    • 最后直接用A1[i]+A2[i+1],然后求出最大值。
      eg.
      index 0 1 2 3 4
      A 8 1 5 2 6
      A1 8 2 7 5 6
      (A2 8 0 3 -1 2)
      A2 8 3 3 2 2
      res 11 5 9 7 -

    2.知识点

    • *max_element()是直接返回最大值;
    • *max_element()是返回最大值的位置,再减去A.begin()就得到index。

    3.实现

    class Solution {
    public:
        int maxScoreSightseeingPair(vector<int>& A) {
            int len = A.size();
            vector<int>  A1, A2, score;
            for(int i=0; i<len; i++){
                A1.push_back(A[i]+i);
                A2.push_back(A[i]-i);
            }
            
            int d = *min_element(A2.begin(), A2.end());
            for(int i=len-1; i>=0; i--){
                d = A2[i]>d?A2[i]:d;
                A2[i] = d;
            }
            
            for(int i=0; i<len-1; i++){
                score.push_back(A1[i] + A2[i+1]);
            }
            
            int res = *max_element(score.begin(), score.end());
            return res;
        }
    };
    
  • 相关阅读:
    postman的本地安装教程
    06-Hibernate中的持久化类
    05-Hibernate的核心API及使用c3p0连接池
    04-Hibernate的常见配置
    03-Hibernate的入门
    02-Hibernate的日志记录
    01-Hibernate框架的概述
    15-struts2 提供的异常处理
    14-struts2的表单标签
    13-struts2中json插件使用
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/10596637.html
Copyright © 2011-2022 走看看