yanswu
yanswu

Reputation: 16

No viable overloaded "="

I've been working on this LeetCode question: https://leetcode.com/problems/maximum-subarray/

Here is my solution:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        vector<int> maxSum [nums.size()];
        int answer = INT_MIN;
        maxSum[0] = nums[0];
        for (int i=1;i<nums.size();i++) {
            maxSum[i] = max(maxSum[i-1]+nums[i], nums[i]);
            answer = max(maxSum[i], answer);
        }
        return answer;
    }
};

and it is throwing an error:

Line 7: Char 21: error: no viable overloaded '='
        (maxSum[0]) = (nums[0]);
        ~~~~~~~~~~~ ^ ~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:692:7: note: candidate function not viable: no known conversion from '__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type' (aka 'int') to 'const std::vector<int, std::allocator<int>>' for 1st argument
      operator=(const vector& __x);
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:706:7: note: candidate function not viable: no known conversion from '__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type' (aka 'int') to 'std::vector<int, std::allocator<int>>' for 1st argument
      operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:727:7: note: candidate function not viable: no known conversion from '__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type' (aka 'int') to 'initializer_list<std::vector<int, std::allocator<int>>::value_type>' (aka 'initializer_list<int>') for 1st argument
      operator=(initializer_list<value_type> __l)
      ^

I've been looking up the reasons for this, but it seems like none of them applies to my case. I've tried adding parentheses around it or checking the types of variables, but I still don't understand what's wrong with my code.

P.S. I realized that I don't need a vector to keep track of the maximum, but I still would like to know why this is happening.

Upvotes: 0

Views: 1890

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70347

vector<int> maxSum[nums.size()];

This declares an array of vectors of integers. You can simply use parentheses to call the std::vector constructor indicating how many slots to pre-allocate and default-initialize.

vector<int> maxSum(nums.size());

Upvotes: 2

Related Questions