Minimum Subarray

题目:

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

Return the sum of the subarray.

分析:

这题目说到底是一个贪心法,就是当sum超过0的时候,强行至零,相当于如果sum超过0了,就从新开始统计下一个subarray。

解法:

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 sum = 0;
        int minSum = INT_MAX;
        for (int i = 0; i < nums.size(); i++) {
            sum += nums[i];
            minSum = min(sum, minSum);
            sum = min(sum, 0);
        }
        return minSum;
    }
};

results matching ""

    No results matching ""