Sum of largest subarray is k - LintCode

Given an array nums and a target value k, find the longest subarray in the array so that the sum of its elements is k. If not, return 0.

 注意事项
数组之和保证在32位有符号整型数的范围内

Example
Given array nums = [1, -1, 5, -2, 3], k = 3, return 4

解析:
子数组[1, -1, 5, -2]的和为3,且长度最大

Given array nums = [-2, -1, 2, 1], k = 1, return 2

解析:
子数组[-1, 2]的和为1,且长度最大

Challenge
Can it be done in O(n) time complexity?

Ideas
Build a Map to store the values ​​and positions of the nums elements. Then modify nums[i] to the sum of nums[0] to nums[i]. If nums[i] is equal to k, then the subarray is nums[0,i] with length i+1. For nums[i], find nums[i]-k in the Map, if there is such an element, and its position p is less than i, the length of the new subarray is ip, and the minimum value is taken.

#ifndef C911_H
#define C911_H
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution {
public:
    /**
    * @param nums: an array
    * @param k: a target value
    * @return: the maximum length of a subarray that sums to k
    */
    int maxSubArrayLen(vector<int> &nums, int k) {
        // Write your code here
        if (nums.empty())
            return 0;
        int res = 0;
        unordered_map<int, int> m;//存放nums中元素的值和位置
        int len = nums.size();
        //nums[i]表示从nums[0]到nums[i]的和
        for (int i = 1; i < len; ++i)
            nums[i] += nums[i - 1];
        for (int i = 0; i < len; ++i)
        {
            //重复元素,存放较小位置
            if (m.find(nums[i]) == m.end())
                m[nums[i]] = i;
        }
        //若nums[i]等于k,子数组为nums[0]到nums[i],长度为i + 1
        for (int i = len - 1; i >= 0; --i)
        {
            if (nums[i] == k)
            {
                res = i + 1;
                break;
            }
        }
        //在m中寻找nums[i]-k,如果存在,且m[nums[i]-k]的值小于等于i
        //说明在nums[0]到nums[i]中,存在子数组的和位k,子数组长度为i - m[nums[i] - k
        for (int i = 0; i < len; ++i)
        {
            if (m.find(nums[i] - k) != m.end() && m[nums[i] - k] <= i)
            {
                res = maxVal(res, i - m[nums[i] - k]);
            }
        }
        return res;
    }
    int maxVal(int a, int b)
    {
        return a > b ? a : b;
    }
};
#endif

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325390101&siteId=291194637
Recommended