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()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,915評論 0 13
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,993評論 0 0
  • title: Optical Character Recognition (OCR)author: Marina ...
    4a87cc38dcbc閱讀 407評論 0 0
  • Introduction What is Bowtie 2? Bowtie 2 is an ultrafast a...
    wzz閱讀 6,166評論 0 5
  • 日念家人一好處,念力加持享幸福! 【先生好】周日接送孩子畫畫,都沒時間做飯啦!干脆蒸了米飯,接孩子回來順便買了個菜...
    風(fēng)瀟瀟blj閱讀 126評論 0 0

友情鏈接更多精彩內(nèi)容