Can anybody explain me what is wrong in my code

Question link -Link

My code -

#include <bits/stdc++.h>

using namespace std;

int main(){
	int t;
	cin>>t;
	int arr[t];
	for(int i=1;i<=t;i++)
		cin>>arr[i];
	sort(arr,arr+t);
	int ans = 0;
	for(int i=1;i<=t;i++){
		int c = arr[i]*i;
		ans = max(c,ans);
	}
	cout<<ans<<endl;
	return 0;
}

Sample Input

4 30 20 53 14

Output

60

But my Output is

159

Indexes in an array of size t is from 0 to t-1 only. But here you are also accessing values at index t that would give garbage value.
You should declare an array of size atleast t+1 as you are using the indexes from 1 to t.

2 Likes
#include <bits/stdc++.h> 
using namespace std;

int main(){
long long n; cin >> n ;
vector<long long> v(n);
for(long long i = 0 ; i < n;i++){
cin >> v[i];
}

sort(v.begin(),v.end());
long long ans = -1;

for(long long i = 0 ; i < n;i++){
long long c = v[i]*((long long)v.size()-i);
ans = max(ans,c);
}

cout << ans <<endl;


return 0;
}
1 Like

You can spot the issue that @wslord mentioned using the right gcc flags:

[simon@simon-laptop][07:59:30]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling sn_23-ZCO14003.cpp
+ g++ -std=c++14 sn_23-ZCO14003.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
+ set +x
Successful
[simon@simon-laptop][07:59:34]
[~/devel/hackerrank/otherpeoples]>echo "4 30 20 53 14" | ./a.out
sn_23-ZCO14003.cpp:14:22: runtime error: index 4 out of bounds for type 'int [*]'
1483742784

(although interestingly, it doesn’t spot the out-of-bounds access at line 10.)

1 Like