HackerRank:Max Array Sum Python3

题目

https://www.hackerrank.com/challenges/max-array-sum/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dynamic-programming

Given an array of integers, find the subset of non-adjacent elements with the maximum sum. Calculate the sum of that subset.

For example, given an array we have the following possible subsets:

Subset Sum
[-2, 3, 5] 6
[-2, 3] 1
[-2, -4] -6
[-2, 5] 3
[1, -4] -3
[1, 5] 6
[3, 5] 8
Our maximum subset sum is .

Function Description

Complete the function in the editor below. It should return an integer representing the maximum subset sum for the given array.

maxSubsetSum has the following parameter(s):

arr: an array of integers
Input Format

The first line contains an integer, .
The second line contains space-separated integers .

Constraints

Output Format

Return the maximum sum described in the statement.

Sample Input 0

5
3 7 4 6 5
Sample Output 0

13
Explanation 0

Our possible subsets are and . The largest subset sum is from subset

Sample Input 1

5
2 1 5 8 4
Sample Output 1

11
Explanation 1

Our subsets are and . The maximum subset sum is from the first subset listed.

Sample Input 2

5
3 5 -7 8 10
Sample Output 2

15
Explanation 2

Our subsets are and . The maximum subset sum is from the fifth subset listed.

解题思路

DP问题要善于用累加的思想,其实核心就是去比较上一个自己和每个间隔和自己相加的最大值

ANSWER

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the maxSubsetSum function below.
def maxSubsetSum(arr):
    dp = []
    dp.append(arr[0])
    dp.append(max(arr[:2]))
    print (arr[2:])
    for a in arr[2:]:
        dp.append(max([
            dp[-2]+a, 
            a, 
            dp[-1]
        ]))
    return dp[-1]

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    res = maxSubsetSum(arr)

    fptr.write(str(res) + '\n')

    fptr.close()

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,979评论 0 13
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 3,004评论 0 0
  • title: Optical Character Recognition (OCR)author: Marina ...
    4a87cc38dcbc阅读 414评论 0 0
  • Introduction What is Bowtie 2? Bowtie 2 is an ultrafast a...
    wzz阅读 6,333评论 0 5
  • 日念家人一好处,念力加持享幸福! 【先生好】周日接送孩子画画,都没时间做饭啦!干脆蒸了米饭,接孩子回来顺便买了个菜...
    风潇潇blj阅读 126评论 0 0

友情链接更多精彩内容