LeetCode练题——53. Maximum Subarray
2024-09-03 02:48:47
1、题目
53. Maximum Subarray——Easy
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
2、我的解法
(1)超时的暴力解法
# -*- coding: utf-8 -*-
# @Time : 2020/2/6 22:15
# @Author : SmartCat0929
# @Email : 1027699719@qq.com
# @Link : https://github.com/SmartCat0929
# @Site :
# @File : 53. Maximum Subarray(超时的暴力算法).py
from typing import List class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSum = -9999999999
if len(nums)>1:
maxSum = -99999
for i in range(0, len(nums)):
for j in range(i, len(nums)):
thisSum = sum(nums[i:j+1])
if thisSum > maxSum:
maxSum = thisSum
return maxSum
elif len(nums)==1:
maxSum=nums[0]
return maxSum
else:
return 0 print(Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
(2)局部最大值(copy大神)
# -*- coding: utf-8 -*-
# @Time : 2020/2/7 16:12
# @Author : SmartCat0929
# @Email : 1027699719@qq.com
# @Link : https://github.com/SmartCat0929
# @Site :
# @File : 53. Maximum Subarray.py from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
tmp = 0
res = float('-inf')
for i in range(n):
if tmp < 0:
tmp = 0
tmp = tmp + nums[i]
res = max(res, tmp)
return res
print(Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
最新文章
- UIScrollView的代理(delegate)
- ActiveMQ初体验
- Java--剑指offer(2)
- 模态视图(modalTrasitionStyle)如何适应不同的版本
- sql 执行动态语句
- 并行程序设计模式--Master-Worker模式
- Struts2拦截器Interceptor执行顺序理解
- hiho_1051_补提交卡
- 【OpenCV入门教程之二】 一览众山小:OpenCV 2.4.8组件结构全解析
- HDU-1078
- jsonp+handler 的实现
- Android开发 学习笔记——HelloWorld
- PC版模块滚动不显示滚动条效果
- mysql基础整理01
- Java名称字符串进行星号处理
- SpringCloud无废话入门01:最简SpringCloud应用
- Java并发编程笔记之ArrayBlockingQueue源码分析
- python中#!/usr/bin/python与#!/usr/bin/env python的区别
- Linux snprintf使用总结
- ZZNU 2095 : 我只看看不写题
热门文章
- 【STM32H7教程】第59章 STM32H7的DAC基础知识和HAL库API
- Codeforces Round #570 (Div. 3) B. Equalize Prices
- 开发板上如何配置apahe2+mysql+php7
- 在Linux系统下安装jdk并配置环境变量
- 整合SSM2
- [人物存档]【AI少女】【捏脸数据】人物鉴赏190
- webview在compileSdkVersion 大于等于23 android6.0以上系统执行js代码异常,但是在compileSdkVersion小于23 android6.0以下系统却执行正常问题
- SpringCloud Netflix Ribbon
- [python]Python 字典(Dictionary) update()方法
- 7_2 最大乘积(UVa11059)<;枚举连续子序列>;