前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >今日营业:每日一题

今日营业:每日一题

作者头像
仇诺伊
发布2020-04-24 10:19:41
2190
发布2020-04-24 10:19:41
举报
文章被收录于专栏:佳爷的后花媛佳爷的后花媛
代码语言:javascript
复制


今天应该开始这一题了,题目如下:





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.



解题思路如下: 把数组的值依次相加,正数的话会一直变大,但是如果出现了负数,就不是最大的了。 应该还有其他的解决方案,欢迎提供,我看了LeetCode的其他解决方案,还是有很多值得学习的。 代码:

代码语言:javascript
复制
# @File    : maximum_subarray.py
# @Date    : 2020-02-08
# @Author  : shengjia

def maxSubArray(nums):
    for i in range(1, len(nums)):
        if nums[i - 1] > 0:
            nums[i] += nums[i - 1]
    print(max(nums))
    return max(nums)


inputs = [-2, 1, -3, 4, -1, 2, 5, -5, 4]
maxSubArray(inputs)

有个大佬的解决如下,感觉还是很6的,鉴于我对python的浅陋(只会用python解一些简单的题),不能在这瞎比比了。

好了,今日营业到此为止,打烊了,晚安! 哦 顺便贴上佳爷练习的地址(https://github.com/ZoeSj/LeetCodeDay),感兴趣的可以一起学习,加油~

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 佳爷的后花媛 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档