leetcode#53Maximum Subarray
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.
思路
这道题要求 求连续的数组值,加和最大。
试想一下,如果我们从头遍历这个数组。对于数组中的其中一个元素,它只有两个选择:
要么加入之前的数组加和之中(跟别人一组)
要么自己单立一个数组(自己单开一组)
所以对于这个元素应该如何选择,就看他能对哪个组的贡献大。如果跟别人一组,能让总加和变大,还是跟别人一组好了;如果自己起个头一组,自己的值比之前加和的值还要大,那么还是自己单开一组好了。
所以利用一个sum数组,记录每一轮sum的最大值,sum[i]表示当前这个元素是跟之前数组加和一组还是自己单立一组好,
————————————————
原文链接:https://blog.csdn.net/mine_song/article/details/61650409
class Solution {public int maxSubArray(int[] nums) {int []sum = new int[nums.length];//sum数组储存每一轮的sumint max= nums[0];sum[0] = nums[0];for(int i=1;i<nums.length;i++){sum[i] = Math.max(sum[i-1]+nums[i],nums[i]);//对于其中一个元素有两种选择,1加入之前数组,2如果自己比和之前数组的和还大则自己一组max = Math.max(max,sum[i]);}return max;}
}
leetcode#53Maximum Subarray相关推荐
- [LeetCode] Maximum Subarray 最大子数组
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- LeetCode 974. Subarray Sums Divisible by K--Python解法--数学题--取模求余
LeetCode 974. Subarray Sums Divisible by K–Python解法–数学题–取模求余 LeetCode题解专栏:LeetCode题解 LeetCode 所有题目总结 ...
- leetcode 974 Subarray Sums Divisible by K
leetcode 974 Subarray Sums Divisible by K 1.题目描述 2.解题思路 3.Python代码 1.题目描述 给定一个整数数组 A,返回其中元素之和可被 K 整除 ...
- [LeetCode] Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- LeetCode Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- LeetCode - Maximum Subarray
题目: Find the contiguous subarray within an array (containing at least one number) which has the larg ...
- LeetCode: Maximum Subarray 解题报告
Maximum Subarray Find the contiguous subarray within an array (containing at least one number) which ...
- leetcode 974. Subarray Sums Divisible by K
974. Subarray Sums Divisible by K 题意:给你一个数组A和一个数K,求改数组有多少连续子序列的和能被K整除. 思路:简单DP.假设sum[i]表示[0-i]的求和,那么 ...
- Leetcode 560. Subarray Sum Equals K
前缀和(prefix sum/cumulative sum) import collectionsclass Solution(object):def subarraySum(self, nums, ...
最新文章
- 面试题:Class.forName 和 ClassLoader 有什么区别?
- Genetic Algorithm遗传算法,两个代码实现例子
- 【转】程序在内存中的分布
- LeetCode 2000. 反转单词前缀
- 生化危机5 / BIOHAZARD5 简直就是一款完美的印钞机?(+2009.4.9)
- Exp3 免杀原理与实践 20164314
- magento 优化 php.ini,PHP.ini配置文件(中文) | Magento UI
- [POI2009]SLO
- 时间选择器Android-PickerView的使用
- RS232串口转USB驱动无法正确识别
- 【AllenNLP入门教程】: 1、基于Allennlp2.4版本的文本分类
- 中兴笔试c语言,中兴笔试题目
- 华为鸿蒙麒麟玉兔_鸿蒙、麒麟、鲲鹏……这是属于中华的浪漫
- 基于ROS使用Arduino控制水泵
- 《银河英雄传说》杨威利经典语录2
- APP测试面试题,总结的很到位,安排!
- 一个最简单的Delphi2010的PNG异形窗口方法
- 基于51单片机的LCD1602电子时钟
- 【虹科】人工智能和工业相机助力瓶盖质量控制
- 利用STM32F103最小系统做C2接口离线烧录器