LintCode--最小子数组

LintCode--minimum-subarray(最小子数组)

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


给定一个整数数组,找到一个具有最小和的子数组。返回其最小和。

样例

给出数组[1, -1, -2, 1],返回 -3

注意

子数组最少包含一个数字


分析:

如果数组全为正,则返回最小值,否则和最大子序列和一样动态规划

时间复杂度 O(n)


代码(C++、Python、Java):

class Solution {
public:
    /**
     * @param nums: a list of integers
     * @return: A integer denote the sum of minimum subarray
     */
    int minSubArray(vector<int> nums) {
        // write your code here
        int n = nums.size();
        int min = nums[0];
        for (int i = 1; i < n; i++)
            if (nums[i] < min)
                min = nums[i];
        if (min > 0) return min;
        int dp = 0, res = 0;
        for (int i = 0; i < n; i++){
            dp += nums[i];
            if (dp > 0) dp = 0;
            if (dp < res) res = dp;
        }
        return res;
    }
};

class Solution:
    """
    @param nums: a list of integers
    @return: A integer denote the sum of minimum subarray
    """
    def minSubArray(self, nums):
        # write your code here
        n = len(nums)
        if n == 0:
            return 0
        min = nums[0]
        for i in range(1, n):
            if nums[i] < min:
                min = nums[i]
        if min > 0:
            return min
        dp = 0
        res = 0
        for i in range(n):
            dp += nums[i]
            if dp > 0:
                dp = 0
            if dp < res:
                res = dp
        return res

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: A integer indicate the sum of minimum subarray
     */
    public int minSubArray(ArrayList<Integer> nums) {
        // write your code
        int n = nums.size();
        int min = nums.get(0);
        for (int i = 1; i < n; i++)
            if (nums.get(i) < min)
                min = nums.get(i);
        if (min > 0) return min;
        int dp = 0, res = 0;
        for (int i = 0; i < n; i++){
            dp += nums.get(i);
            if (dp > 0) dp = 0;
            if (dp < res) res = dp;
        }
        return res;
    }
}



你可能感兴趣的:(算法,lintcode)