The outputs:
Input the length of array: 12
1 3 3 8 7 2 2 7 2 5 4 1
scan and identify whether 1 exists or not
There is an element 1 in the array
The corresponding codes:
//step_1 generate a random array with random values
// step_2 suppose the value in array is prices of a specific prices
// step_3 write a function to get your most profit
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
void generate_array(int *&arr, int len);
void display_array(int arr[], int len);
int greedy_solution(int arr[], int len);
int dp_solution(int arr[], int len);
int find_existance(int arr[], int len, int ele);
int main()
{
srand((unsigned)time(NULL));
cout << "Input the length of array: ";
int len;
cin >> len;
int *a;
generate_array(a, len);
display_array(a, len);
int ele = rand() % 9;
cout << "\nscan and identify whether " << ele << " exists or not" << endl;
int identifier = find_existance(a, len, ele);
if (identifier == 0){
cout << "There is an element " << ele << " in the array" << endl;
}else{
cout << "There isn't an element " << ele << " in the array" << endl;
}
free(a);
return 0;
}
void generate_array(int *&arr, int len)
{
arr = new int[len];
for (int i = 0; i < len; i++){
arr[i] = rand() % 8 + 1;
}
}
void display_array(int arr[], int len)
{
for (int i = 0; i < len; i++) {
cout << setw(3) << arr[i] ;
}
}
int find_existance(int arr[], int len, int ele)
{
int flag = 1; // this means this program guess the element ele does not exist in the array
for (int i = 0; i < len; i++) {
if (arr[i] == ele){
flag = 0;
break;
}
}
return flag;
}
int greedy_solution(int arr[], int len)
{
int max_profit = 0;
for (int i = 1; i < len; i++) {
if (arr[i] > arr[i-1]){
max_profit += (arr[i] - arr[i-1]) ;
}
}
return max_profit;
}
int dp_solution(int arr[], int len)
{
int dp_0 = 0;
int dp_1 = -arr[0];
for (int i = 1; i < len; i++){
dp_0 += max(dp_0, dp_1 + arr[i]);
dp_1 += max(dp_1, dp_0 - arr[i]);
}
return dp_0;
}