首页 > 其他分享 >[LeetCode]Maximum Subarray

[LeetCode]Maximum Subarray

时间:2023-02-02 15:36:59浏览次数:42  
标签:contiguous nums int sum Maximum ans 序列 Subarray LeetCode


Question
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.


本题难度Medium。

【复杂度】
时间 O(N) 空间 O(1)

【思路】
为了求整个字符串最大的子序列和,我们将先求较小的字符串的最大子序列和。这里我们从后向前、从前向后计算都是可以的。在从前向后计算的方法中,我们将第i个元素之前最大的子序列和存入变量​​​sum​​​中,对第i+1个元素来说,它的值取决于​​sum​​​,如果​​sum​​是负数,那就没有必要加上它,因为这只会拖累子序列的最大和。如果是正数就加上它。

【注意】
第4、5行别写成:

int ans=0;
int sum=0;

【代码】

public class Solution {
public int maxSubArray(int[] nums) {
int size=nums.length;
int ans=nums[0];
int sum=nums[0];
//invariant
for(int i=1;i<size;i++){
sum=(sum>0)?sum+nums[i]:nums[i];
ans=Math.max(ans,sum);
}
//ensure
return ans;
}
}

参考

​​[Leetcode] Maximum Subarray 子序列最大和​​


标签:contiguous,nums,int,sum,Maximum,ans,序列,Subarray,LeetCode
From: https://blog.51cto.com/u_9208248/6033690

相关文章

  • [LeetCode]Spiral Matrix
    QuestionGivenamatrixofmxnelements(mrows,ncolumns),returnallelementsofthematrixinspiralorder.Forexample,Giventhefollowingmatrix:[[1......
  • [LeetCode]N-Queens II
    QuestionFollowupforN-Queensproblem.Now,insteadoutputtingboardconfigurations,returnthetotalnumberofdistinctsolutions.本题难度Hard。【思路】​N......
  • [LeetCode]Group Anagrams
    QuestionGivenanarrayofstrings,groupanagramstogether.Forexample,given:[“eat”,“tea”,“tan”,“ate”,“nat”,“bat”],Return:[[“ate”,“......
  • [LeetCode]Jump Game II
    QuestionGivenanarrayofnon-negativeintegers,youareinitiallypositionedatthefirstindexofthearray.Eachelementinthearrayrepresentsyourmaximu......
  • [LeetCode]Rotate Image
    QuestionYouaregivenannxn2Dmatrixrepresentinganimage.Rotatetheimageby90degrees(clockwise).Followup:Couldyoudothisin-place?本题难度Mediu......
  • 1877.minimize-maximum-pair-sum-in-array 数组中最大数对和的最小值
    问题描述1877.数组中最大数对和的最小值解题思路贪心将数组从小到大排序,最小最大配对,次小次大配对,依次配对,结果就是这些配对和的最大值。代码classSolution{publi......
  • LeetCode 1143_ 最长公共子序列
    LeetCode1143:最长公共子序列题目给定两个字符串text1和text2,返回这两个字符串的最长公共子序列的长度。如果不存在公共子序列,返回0。一个字符串的子序列......
  • 【DFS】LeetCode 124. 二叉树中的最大路径和
    题目链接124.二叉树中的最大路径和思路一个子树内部的最大路径和=左子树提供的最大路径和+根节点值+右子树提供的最大路径和。即dfs(root.left)+root.val+dfs(r......
  • LeetCode - 709. To Lower Case
    题目ImplementfunctionToLowerCase()thathasastringparameterstr,andreturnsthesamestringinlowercase.Example1:Input:"Hello"Output:"hello"Example2:......
  • LeetCode - 344. Reverse String
    题目Writeafunctionthatreversesastring.Theinputstringisgivenasanarrayofcharacterschar[].Donotallocateextraspaceforanotherarray,youmust......