Man goes places problem

There are N places, numbered 1,2,…,N. For each i (1≤i≤N), the cost of reaching place i is hi. There is a man who is initially on place 1. He will repeat the following action some number of times to reach place N: If the man is currently at place i, he will go to place i+1 or place i+2 i.e. maximum 2 jumps allowed. Here, a cost of |hi−hj| is incurred, where j is the place where the man goes. Find the minimum possible total cost incurred before the man reaches place N.
Input
The input line contains T, denoting the number of testcases. Each testcase contains two lines. First line contains N size of array, second line contains elements of array.

Constraints
1 <= T <= 10
2 ≤ N ≤ 10^5
1 ≤ hi ≤ 10^4
Output
Print the minimum possible total cost incurred.
Input:
1
4
10 30 40 20

Output:
30

Explanation:
Testcase 1: If we follow the path 1→ 2→ 4, the total cost incurred would be |10−30|+|30−20|=30.
my code it worked .. all test case passed

#include<bits/stdc++.h> 
using namespace std; 
int mgp( vector<int> &arr, int n ) 
{ 
   int c1,c2; int dp[n]; 
   dp[0] = 0;
   dp[1] = abs(arr[1] - arr[0]);
    for (int i = 2; i <= n-1; i++)  
    {
        c1=dp[i - 2]   + abs(arr[i] - arr[i - 2]);
        //cout<< c1<<' ';
        c2=dp[i - 1] + abs(arr[i] - arr[i - 1]);
        //cout<< c2<<' ';
        dp[i] =  min(c1,c2);
       // cout<< dp[i]<<' ';
     }
    return dp[n-1];
} 
  

int main() 
{ 
  vector<int>  arr ;
  int n,x1,t ;
  cin >> t;
  for(int j=0;j < t; j++)
   {
       cin >> n;
  for(int i=0;i < n; i++)
  {
      cin >> x1;
      arr.push_back(x1);
  }
  cout<<  mgp( arr, n ) ; 
  }
  return 0; 
}
Comments (1)