Hackerrank-Arrays-Array Manipulation-Maximum value in an array after m range increment operations

给你一个长度为N的列表,列表的初始值全是0。对此列表,你要进行M次查询,输出列表种最终N个值的最大值。对每次查询,给你的是3个整数——a,b和k,你要对列表中从位置a到位置b范围内的(包含a和b)的全部元素加上k。
 

输入格式

第一行包含两个整数 N和 M
接下来 M行,每行包含3个整数 ab 和 k
列表中的数位置编号为从1到 N
 

输出格式

单独的一行包含 最终列表里的最大值

约束条件

3 <= N <= 10^7
1 <= M <= 2*10^5
1 <= a <= b <= N
0 <= k <= 10^9

输入样例 #00:

5 3
1 2 100
2 5 100
3 4 100

输出样例 #00: 200

两种方法:

1. A naive method is to perform each operation on given range and then at last find the maximum number.

2. Efficient method : Perform two things in a single operation:
     a- Add k-value to only lower_bound-1 of a range.

     b- Reduce upper_bound  index by k-value (注意upper bound 不要超出len(list))

     c- after all operations, calculate accumulative sum and check the maximum sum

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the arrayManipulation function below.
def arrayManipulation0(n, queries): #fail to execute within the time limits for some cases
    arr=[]
    for i in range(n):
        arr.append(0)
    for query in queries:
        for j in range(query[0]-1,query[1]):
            arr[j]+=query[2]
    return max(arr)

#try a more efficient way
def arrayManipulation(n, queries):
    arr=[]
    for i in range(n):
        arr.append(0)
    for query in queries:
        arr[query[0]-1]+=query[2] #change the lower bound 
        if query[1]<=n-1:  
            arr[query[1]]+=-query[2]  #change the upper bound
    maximum=0
    sumarr=0
    for i in range(n):
        sumarr+=arr[i] #calculate accumulative sum, which denotes the actual values in the final array
        if sumarr>maximum: 
            maximum=sumarr
    return maximum
    

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

    nm = input().split()

    n = int(nm[0])

    m = int(nm[1])

    queries = []

    for _ in range(m):
        queries.append(list(map(int, input().rstrip().split())))
    
    result = arrayManipulation(n, queries)

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

    fptr.close()
发布了128 篇原创文章 · 获赞 90 · 访问量 4852

猜你喜欢

转载自blog.csdn.net/weixin_45405128/article/details/103996416