Skip to content

Commit 63de16e

Browse files
committed
local
1 parent d6e0aee commit 63de16e

File tree

2 files changed

+25
-47
lines changed

2 files changed

+25
-47
lines changed

18-Programming-4kids/10_homework_05_answer.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// By Basel Bairkdar https://www.facebook.com/baselbairkdar
1+
// By Basel Bairkdar https://www.facebook.com/baselbairkdar - modified
22
#include<iostream>
33
using namespace std;
44

@@ -7,9 +7,6 @@ int main() {
77

88
int n, a[N];
99

10-
// let's use some big value and later minimize
11-
int mn = 10000000;
12-
1310
cin >> n;
1411
for (int i = 0; i < n; i++)
1512
cin >> a[i];
@@ -19,11 +16,16 @@ int main() {
1916
such that i < j
2017
this can be done using nested for loops.
2118
**/
19+
// let's use some big value and later minimize
20+
int mn;
21+
bool first_time = true;
22+
2223
for (int i = 0; i < n; i++) {
2324
for (int j = i + 1; j < n; j++) {
2425
int tmp = a[i] + a[j] + j - i;
25-
if (tmp < mn) {
26+
if (first_time || tmp < mn) {
2627
mn = tmp;
28+
first_time = false;
2729
}
2830
}
2931
}
Lines changed: 18 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,24 @@
1-
// By Amr Fahim https://www.facebook.com/amrfahim2020
2-
// Homework 7 solution
31
#include <iostream>
4-
using namespace std ;
2+
using namespace std;
53

6-
// We use 2 frequency arrays one for the positive numbers and the other for the negative
4+
int main() {
5+
int n;
6+
cin >> n;
7+
const int MAX = 270 + 500 + 1;
8+
int frequency[MAX] = { 0 }; // initialize with zeros. You can't do for other values (e.g. 1) this way.
79

8-
int n , neg_num[500 +10] , pos_num[270 + 10 ] , max_num , max_freq ;
10+
for (int i = 0; i < n; i++) {
11+
int value;
12+
cin >> value;
913

10-
int main()
11-
{
12-
cin >> n ;
13-
int arr[n] ;
14-
15-
for (int i = 0 ; i < n ;i++ )
16-
{
17-
cin >> arr[i] ;
18-
// Check the sign of the input value
19-
//to know which array we should add the deal with
20-
if (arr[i] >= 0 )
21-
{
22-
pos_num[arr[i]]++ ;
14+
value += 500; // shift all values to be positive
15+
frequency[value]++;
16+
}
2317

24-
// Comparing the value we have now with the max value
25-
if (pos_num[arr[i]] > max_freq )
26-
{
27-
max_freq = pos_num[arr[i]] ;
28-
max_num = arr[i] ;
29-
30-
}
31-
32-
}
33-
else if (arr[i] < 0 )
34-
{
35-
neg_num[arr[i]]++ ;
36-
37-
// Comparing the value we have now with the max value
38-
if (neg_num[arr[i]] > max_freq )
39-
{
40-
max_freq = neg_num[arr[i]] ;
41-
max_num = arr[i] ;
42-
}
43-
}
44-
45-
46-
}
47-
cout << max_num <<" has repeated " << max_freq <<" times " ;
18+
int mx_pos = 0;
19+
for (int i = 0; i < MAX; i++) {
20+
if (frequency[mx_pos] < frequency[i])
21+
mx_pos = i;
22+
}
23+
cout << mx_pos - 500 << " has repeated " << frequency[mx_pos] << " times ";
4824
}

0 commit comments

Comments
 (0)