Lintcode: Minimum Subarray 解题报告

本文介绍了一种求解最小子数组和的算法,通过将问题转换为求最大和子数组问题,采用滑动窗口方法进行高效计算。文章提供了详细的算法步骤及Java实现代码。
Minimum Subarray

原题链接: http://lintcode.com/zh-cn/problem/minimum-subarray/#

Given an array of integers, find the subarray with smallest sum.

Return the sum of the subarray.

注意

The subarray should contain at least one integer.

样例

For [1, -1, -2, 1], return -3

标签 Expand

SOLUTION 1:

1. 我们把整个array * -1,把它转化为求最大和的题目。

2. 然后我们可以使用Sliding window的方法来做。记录一个sum,如果发现sum<0 则丢弃,否则不断把当前的值累加到sum,

3. 每计算一次sum,求一次max.

4. 返回-max即可。

 1 public class Solution {
 2     /**
 3      * @param nums: a list of integers
 4      * @return: A integer indicate the sum of minimum subarray
 5      */
 6     public int minSubArray(ArrayList<Integer> nums) {
 7         // write your code
 8         
 9         int len = nums.size();
10         
11         int max = Integer.MIN_VALUE;
12         int sum = 0;
13         for (int i = 0; i < len; i++) {
14             if (sum < 0) {
15                 sum = -nums.get(i);
16             } else {
17                 sum += -nums.get(i);
18             }
19             
20             max = Math.max(max, sum);
21         }
22         
23         return -max;
24     }
25 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/array/SubarraySum.java

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值