广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python编写PAT 1007 Max
  • 663
分享到

python编写PAT 1007 Max

PATpythonMax 2023-01-31 00:01:31 663人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

wenzongxiao1996 2019.4.3 题目 Given a sequence of K integers { N​1, N2, ..., N​K}. A continuous subsequence is defined

wenzongxiao1996
2019.4.3

题目

Given a sequence of K integers { N​1, N2, ..., N​K}. A continuous subsequence is defined to be { N​i, N​i+1, ..., N​j} where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space.

Output Specification:
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:
10
-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4

暴力解法(超时了)

def seq_sum(s):
    """求序列的所有元素之和"""
    result = 0
    for i in range(len(s)):
        result += s[i]
    return result

def main():
    n = int(input())
    seq = [int(i) for i in input().split()]
    max = -1
    pos_i = 0
    pos_j = n-1
    for i in range(n):
        for j in range(i,n):
            sum_temp = seq_sum(seq[i:j+1])
            if sum_temp > max:
                max = sum_temp
                pos_i = i
                pos_j = j
    if max < 0:
        print(0,seq[pos_i],seq[pos_j])
    else:
        print(max,seq[pos_i],seq[pos_j])

if __name__ == '__main__':
    main()

分治法

def division_solution(seq,left,right):
    if left == right: # 递归出口
        if seq[left] >= 0:
            return left,right,seq[left]
        else:
            return left,right,-1
    center = (left+right)//2 # 地板除

    # 从中间到左边的最大子串
    sum_left = 0
    max_sum_left = -1  # 一定要设为负数
    pos_left = left   # 要返回下标
    for i in range(left,center+1)[::-1]:  # 反向迭代
        sum_left += seq[i]
        if sum_left >= max_sum_left:
            max_sum_left = sum_left
            pos_left = i

    # 从中间到右边的最大子串
    sum_right = 0
    max_sum_right = -1  # 一定要设为负数
    pos_right = right  # 要返回下标
    for i in range(center+1,right+1):
        sum_right += seq[i]
        if sum_right > max_sum_right:
            max_sum_right = sum_right
            pos_right = i

    # 递归求解左右两个子问题
    i_left,j_left,max_left_sum = division_solution(seq,left,center)
    i_right,j_right,max_right_sum = division_solution(seq,center+1,right)

    if max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) < 0:
        return left,right,-1
    else:
        if max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) == max_left_sum:
            return i_left,j_left,max_left_sum
        elif max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) == max_right_sum:
            return i_right,j_right,max_right_sum
        else:
            return pos_left,pos_right,max_sum_left+max_sum_right


def main():
    n = int(input())
    seq = [eval(i) for i in input().split()]
    i,j,sum_max = division_solution(seq,0,n-1)
    if sum_max < 0:
        print(0,seq[0],seq[-1])
    else:
        print(sum_max,seq[i],seq[j])

if __name__ == '__main__':
    main()

动态规划

def main():
    n = int(input())
    seq = [eval(i) for i in input().split()]
    sum_max = -1
    pos_i = 0
    pos_i_temp = 0 # 最大子序列的左下标不能随意更改,只有找到了更大的子串才能改,用这个变量先保存着当前寻找的子串的左下标
    pos_j = n-1
    sum_temp = 0
    for i in range(n):
        sum_temp += seq[i]
        if sum_temp > sum_max:
            sum_max = sum_temp
            pos_j = i
            pos_i = pos_i_temp
        elif sum_temp < 0:# 和小于0的子串不需要考虑
            sum_temp = 0
            pos_i_temp = i+1
    if sum_max < 0:
        print(0,seq[0],seq[-1])
    else:
        print(sum_max,seq[pos_i],seq[pos_j])

if __name__ == '__main__':
    main()

谢谢观看!敬请指正!
参考博客:https://www.cnblogs.com/allzy/p/5162815.html
原题链接:Https://pintia.cn/problem-sets/994805342720868352/problems/994805514284679168

--结束END--

本文标题: python编写PAT 1007 Max

本文链接: https://www.lsjlt.com/news/181696.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python编写PAT 1007 Max
    wenzongxiao1996 2019.4.3 题目 Given a sequence of K integers { N​1, N2, ..., N​K}. A continuous subsequence is defined...
    99+
    2023-01-31
    PAT python Max
  • Python 脚本编写
    学习内容: Python 安装和环境设置 运行和修改 Python 脚本 与用户输入交互 处理异常 读写文件 导入本地、标准和第三方模块 在解释器中进行实验 检查计算机是否安装了 Python ? 在终端窗口输入如下指令,并...
    99+
    2023-01-31
    脚本 Python
  • python fabric 编写SSH
    #-*- coding:utf8 -*- from fabric import Connection class linuxOper(object):     def __init__(self,ipaddr,user='root',pa...
    99+
    2023-01-31
    python fabric SSH
  • Python 之vim编写python自
    Pydiction :vim - python自动补全插件插件的安装如下:1.下载插件包https://github.com/vim-scripts/Pydiction 可以直接下载,也可git下载 [root@localhost ~]# ...
    99+
    2023-01-31
    Python vim python
  • Python - 利用python编写的
    memcached作为缓存文件服务,默认是操作系统里面是可以直接yum -y install memcached进行安装的。/etc/init.d/memcached 是属于系统shell编写的管理脚本,下面这个脚本是python脚本编写出...
    99+
    2023-01-31
    Python python
  • 用python编写一个小程序,如何用python编写软件
    大家好,给大家分享一下用python编写一个小程序,很多人还不知道这一点。下面详细解释一下。现在让我们来看看! 1、python可以写手机应用程序吗? 我想有人曲解意思了,人家说用python开发渣蔽一个手机app,不是说用手机敲写py...
    99+
    2023-10-22
    python
  • 用python编写用户登录界面,用python编写登录程序
    大家好,小编为大家解答用python编写用户登录界面的问题。很多人还不知道用python编写登录程序,现在让我们一起来看看吧! 1、想用python编写一个脚本,登录网页,在网页里做一系列操作,应该怎样实现 python编写一个脚本的腊...
    99+
    2023-09-30
    网络
  • 怎么编写Python脚本
    本篇内容介绍了“怎么编写Python脚本”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!Streamlit是第一个专门针对机器学习和数据科学团...
    99+
    2023-06-02
  • python如何编写函数
    小编给大家分享一下python如何编写函数,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!python的数据类型有哪些python的数据类型:1. 数字类型,包括int(整型)、long(长整型)和float(浮点型)。2....
    99+
    2023-06-14
  • VsCode下编写怎么Python
    本篇内容介绍了“VsCode下编写怎么Python”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!VsCode的全称是Visual Studi...
    99+
    2023-06-27
  • 如何编写 Python 程序
    如何编写 Python 程序 从今以后,保存和运行 Python 程序的标准步骤如下: 对于 PyCharm 用户 打开 PyCharm。 以给定的文件名创建新文件。 输入案例中给出的代码。 右键并运行当前文件。 注意:每当你需要提供...
    99+
    2023-01-31
    程序 Python
  • Python——编写类装饰器
    编写类装饰器类装饰器类似于函数装饰器的概念,但它应用于类,它们可以用于管理类自身,或者用来拦截实例创建调用以管理实例。 -----------------------------------------------------------...
    99+
    2023-01-31
    Python
  • 用python编写maya插件
    1. python的安装 在Eclipse中安装pydev环境,pydev更新地址为:  http://pydev.org/updates 2. 配置python环境: 打开Eclipse菜单Window/Preferences,在PyD...
    99+
    2023-01-31
    插件 python maya
  • mac使用vim编写Python
    1)打开终端,输入cd + 文件夹路径 链接到你要创建的py文件路径 2)输入 vim hello.py 使用vim命令新建hello.py文件,按 i 进入编辑模式 3)输入自己的代码#!/usr/bin/env python3 p...
    99+
    2023-01-31
    mac vim Python
  • 怎么编写Python程序
    本篇内容介绍了“怎么编写Python程序”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!编写代码的工具交互式环境我们打开Windows的“命令...
    99+
    2023-06-01
  • python编写登录接口
    要求: 输入用户名密码       认证成功显示欢迎信息    输错三次以后锁定 代码如下: # Author:YKwhile(True): select=input('请问是注册还是登录') if select == '注册...
    99+
    2023-01-30
    接口 python
  • python 编写管理redmine的相
    最近公司在使用redmine来管理项目,为了便利维护,用python写了两个小程序,和大家分享一下启动和关闭:#!/usr/bin/env python'''Use this script to change redmine status(...
    99+
    2023-01-31
    python redmine
  • python编写登录接口(上)
    中途经过了好几天都没有动手了,得坚持下去啊刚看了Alex老师的视频,其中有个题目如下:编写登录接口-输入用户密码-认证成功后显示欢迎信息-输错三次后锁定# -*- coding: cp936 -*-#用户名保存在一个文件名为user.txt...
    99+
    2023-01-31
    接口 python
  • Python 编写自己的异常
            所有的异常都是在Python或者它的标准库中提前定义好的。根据自己的目的可以使用任意的异常类型,同时也可以自己定义异常类型,用来处理程序中可能会出现的特殊情况。        一个异常是一个类,即类Exception的一个子...
    99+
    2023-01-31
    自己的 异常 Python
  • python编写五子棋游戏
    本文实例为大家分享了python编写五子棋游戏的具体代码,供大家参考,具体内容如下 游戏代码及部分注释 import pygame #导入pygame游戏模块 import time ...
    99+
    2022-06-02
    python 五子棋
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作