#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {int T,N;int sum=0;
cin>>T;
while(T!=0)
{
cin>>N;
int arr[N];
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
for(int i=0;i<N-1;i++)
{
sum=sum+abs(arr[i+1]-arr[i])-1;
}
cout<<sum<<endl;
sum=0;
T--;
}
return 0;
}//this was my code,but it gave wrong answer.Can anyone help me with this
Use long long for sum.
1 Like
The answer may not fit in an integer. Make sum a long long instead.
1 Like
but int can store no’s upto 2^31-1,then why can’t it store sum int this case,where Si<10^6
1 Like
Let’s take into account the worst-case:-
Length of string -> 10^5
Elements of the string -> 1, 10^6, 1, 10^6, 1, 10^6, 1…so on
Here we can see ->abs(s[i] - s[i-1]) = ((10^6) - 1) ≈ 10^6
And if we do this for all the elements, then the total will be around ≈ (10^6) * (10^5) = 10^11
Range of int -> (-2,147,483,648) to (2,147,483,647)
From this we can clearly see 10^11 is out of the int range
2 Likes
thanks for the explaination
1 Like
DO THIS IN PYTHON:
for _ in range(int(input())):
x = int(input())
arr = list(map(int,input().split()))
l = []
for i in range(len(arr)-1):
if arr[i+1] > arr[i]:
l.append(arr[i+1] - arr[i])
elif arr[i+1]<arr[i]:
l.append(arr[i]-arr[i+1])
m = len(l)
print ((sum(l)) - m)