Machine Learning Algorithm in C
Hey guys! I am really glad that I discovered this forum when I began programming.
However, I was recently given a homework assignment that I have some hard time coping with. Here are the instructions:
Several cells are arranged one after the other in a straight line. In i-th cell, a given integer ai is written (i=1,2, …, N). I start from the first cell at the left end and move right; I can choose to jump into the next cell, or into the next of the next cell. Every time I entered a cell i, I have to pay | ai | dollars, when ai is negative, or to receive ai dollars, when ai is nonnegative. At most, how many dollars can I earn?
Input: Integer values of N, a1, a2, …., aN, separated by spaces.
Output: One integer equals to the wanted profit.
Constraints: 0 < N < 100; -100 < ai < 100 for each ai
Example
Input
7 2 -1 3 –2 -1 6 -5
Output
10
I tried several approaches, but the best I got after the test checks on the submission page is 5/10. I soon realized my algorithm is frankly a mess. I am posting below my latest solution and would be happy if you can help me out with some tips or guidelines.
Code:
#include <stdio.h>
int main()
{
int n,array[100];
int i = 0;
int sum = 0;
if(scanf("%d",&n)){};
for(i=0;i<n;i++){
if(scanf("%d",&array[i])){}
}
for(i=0;i<n;i++)
{
if(array[i] >= 0)
{
sum += array[i];
}
else if(array[i] < 0 && array[i+1] < 0)
{
if(array[i] > array[i+1])
{
sum += array[i];
}
else if(array[i] <= array[i+1])
{
sum += array[i+1];
i++;
}
}
}
printf("%d", sum);
return 0;
}