Continuous Subarray Sum

本文介绍了一种高效算法来解决最大连续子数组求和的问题,即找出整数数组中连续子数组的最大和,并返回该子数组的起始与结束索引。通过动态规划的方法,实现了O(n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone)

Example

Give A = [-3, 1, 3, -3, 4], return [1,4].

分析:

max(i) = {max(i - 1) + A[i] if max(i - 1) >= 0, otherwise, A[i]}

 1 public class Solution {
 2     /**
 3      * @param A an integer array
 4      * @return  A list of integers includes the index of the first number and the index of the last number
 5      * cnblogs.com/beiyeqingteng/
 6      */
 7     public ArrayList<Integer> continuousSubarraySum(int[] A) {
 8         if (A == null || A.length == 0) return null;
 9         
10         ArrayList<Integer> list = new ArrayList<Integer>();
11         // initialization
12         int preMax = A[0];
13         int startIndex = 0;
14         int tempMax = A[0];
15         list.add(0);
16         list.add(0);
17         
18         for (int i = 1; i < A.length; i++) {
19             if (preMax < 0) {
20                 preMax = A[i];
21                 startIndex = i;
22             } else {
23                 preMax = A[i] + preMax;
24             }
25             // update
26             if (preMax > tempMax) {
27                 list.clear();
28                 list.add(startIndex);
29                 list.add(i);
30                 tempMax = preMax;
31             }
32         }
33         return list;
34     } 
35 }

转载请注明出处:cnblogs.com/beiyeqingteng/

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5631733.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值