当前位置:网站首页>Greedy - 53. Maximum subarray sum
Greedy - 53. Maximum subarray sum
2022-07-28 03:41:00 【Xiao Zhao, who is working hard for millions of annual salary】
1 Title Description
- Maximum subarray and
Give you an array of integers nums , Please find a continuous subarray with the largest sum ( A subarray contains at least one element ), Return to its maximum and .
Subarray Is a continuous part of the array .
2 Title Example
Example 1:
Input :nums = [-2,1,-3,4,-1,2,1,-5,4]
Output :6
explain : Continuous subarray [4,-1,2,1] And the biggest , by 6 .
Example 2:
Input :nums = [1]
Output :1
Example 3:
Input :nums = [5,4,-1,7,8]
Output :23
source : Power button (LeetCode)
link :https://leetcode.cn/problems/maximum-subarray
3 Topic tips
1 <= nums.length <= 105
-104 <= nums[i] <= 104
4 Ideas
Where is greedy ?
If -2 1 together , When calculating the starting point , It must be from 1 Start calculating , Because negative numbers only lower the sum , This is the place of greed !
Local optimum : At present “ Continuous and " Give up immediately when it's negative , Recalculate from the next element " Continuous and ", Because negative numbers plus the next element “ Continuous and " It's just getting smaller .
The best in the world : Select the maximum " Continuous and ”
In the case of local optimization , And record the maximum “ Continuous and ”, We can deduce the global optimal .
From a code perspective : Traverse nums, Start from scratch count The cumulative , If count Once you add nums[i] It becomes negative , Then we should start from nums[i+1] Start from 0 The cumulative count 了 , Because it has become negative count, It will only drag down the total .
This is equivalent to continuously adjusting the starting position of the maximum suborder and interval in the violent solution .
Then some students asked , There is no need to adjust the end position of the interval ? How to get the maximum " Continuous and " Well ?
The end position of the interval , In fact, if count Got the maximum value , Recorded in time . For example, the following code :
if (count > result) result = count;
This is equivalent to using result Record the maximum suborder and interval sum ( In disguise, the end position is adjusted ).
The starting position of red is greedy. Every time you take count When it's positive , Start the statistics of an interval .
Time complexity :O(n)· Spatial complexity :O(1)
Of course, the title doesn't say if the array is empty , What should be returned , So if the array is empty, everything can be returned .
Many students think that if the input use cases are -1, Or all negative numbers , The result of this greedy algorithm is 0, This is another classic case that proves that brain hole simulation is unreliable , I suggest you run the code and try , You know the , Will also understand why result To initialize to the minimum negative number .
5 My answer
class Solution {
public int maxSubArray(int[] nums) {
if (nums.length == 1){
return nums[0];
}
int sum = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i < nums.length; i++){
count += nums[i];
sum = Math.max(sum, count); // Take the maximum value of interval accumulation ( It is equivalent to continuously determining the termination position of the maximum subsequence )
if (count <= 0){
count = 0; // It is equivalent to resetting the starting position of the maximum sub order , Because when you encounter a negative number, you must pull down the sum
}
}
return sum;
}
}
边栏推荐
- tensorboard使用记录
- How to uninstall clean ZABBIX service? (super detailed)
- 玩一玩WolframAlpha计算知识引擎
- ES6 从入门到精通 # 07:解构赋值
- The latest version of pagoda installs the zip extension, and PHP -m does not display the processing method
- 动态规划——63. 不同路径 II
- SAP UI5 FileUploader 控件深入介绍 - 为什么需要一个隐藏的 iframe 试读版
- Daily practice ----- realize the lottery function of two-color ball. Rules: Six non repeating numbers are randomly selected from 36 red balls, and one from 15 basketball is randomly selected to form a
- Malloc, free, calloc, realloc dynamic memory development functions in dynamic memory management
- Version compatibility issues
猜你喜欢

The wonderful use of asemi rectifier bridge GBPC3510 in DC brush motor

MySQL stored procedures use cursors to synchronize data between two tables

Volvo: what on earth does the deep-rooted "sense of security" rely on?

20220727使用汇承科技的蓝牙模块HC-05配对手机进行蓝牙串口的演示

动态规划——509. 斐波那契数

沃尔沃:深入人心的“安全感” 究竟靠的是什么?

Redis basic operation

每周推荐短视频:如何正确理解“精益”这个词?

Server memory failure prediction can actually do this!

Daily practice ----- realize the lottery function of two-color ball. Rules: Six non repeating numbers are randomly selected from 36 red balls, and one from 15 basketball is randomly selected to form a
随机推荐
Win11 how to rename an audio device
An article grasps the calculation and processing of date data in PostgreSQL
单调栈——42. 接雨水——面大厂必须会的困难题
我的创作纪念日
Swift中的协议
【OPENVX】对象基本使用之vx_lut
[P4] solve the conflict between local file modification and library file
最新版宝塔安装zip扩展,php -m 不显示的处理方法
动态规划——63. 不同路径 II
Mysql基础篇(创建、管理、增删改表)
How to uninstall clean ZABBIX service? (super detailed)
How to solve the problem of win11 black desktop background?
AI chief architect 12 AICA Baidu OCR vertical large-scale landing practice
高等数学(第七版)同济大学 习题3-5 个人解答
Xctf attack and defense world web master advanced area php2
【论文笔记】基于深度学习的移动机器人自主导航实验平台
每日练习------实现双色球的彩票功能。规则:从36个红球中随机选择不重复的6个数,从15个篮球中随机选择1个组成一注彩票。可以选择买多注。
Redis source code analysis (who says C language can't analyze it?)
Tungsten Fabric SDN — BGP as a Service
LightPicture – 精致图床系统