0
class Solution {
    public:
    int change(int amount, vector<int>& coins) {
        vector<unsigned int > dp(amount+1, 0);
        dp[0]=1;
        for (int value: coins){
            for (int i=value; i<amount+1; ++i){
                dp[i]+=dp[i-value];
            }
        }
        return dp[amount]; 
    }
};

this code works fine and runs on all the test cases

but .. this does not (only difference is the use of int instead of unsigned int)

class Solution {
    public:
    int change(int amount, vector<int>& coins) {
        vector<int > dp(amount+1, 0);
        dp[0]=1;
        for (int value: coins){
            for (int i=value; i<amount+1; ++i){
                dp[i]+=dp[i-value];
            }
        }
        return dp[amount]; 
    }
};

error- Line 8: Char 22: runtime error: signed integer overflow: 27131803 + 2123074792 cannot be represented in type 'value_type' (aka 'int') (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:17:22

6
  • 1
    After attempting to format them equally, the two samples appears to be identical. Is the format the only difference between the two? Commented Apr 15 at 6:52
  • i edited the question please see again Commented Apr 15 at 6:56
  • 2
    As the error indicates there is an arithmetic overflow when using int instead of unsigned int. A 32-bit int has a maximum value of 2,147,483,647 while a 32-bit unsigned int has a maximum value of 4,294,967,295. en.cppreference.com/w/cpp/language/types Commented Apr 15 at 13:49
  • @JayBuckman that is not the problem as i have also used long long int, nut still it didn't work Commented Apr 15 at 16:13
  • Do you get the same error about "signed integer overflow", type 'int' when you use long long int? Commented Apr 15 at 18:50

1 Answer 1

0

To avoid overflow in addition operations, if all operands are positive integers and the ranges are known, during computation you can attempt to use uint32_t or uint64_t to prevent overflow

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.