Sherlock and Cost


Problem Statement :


In this challenge, you will be given an array B and must determine an array A. There is a special rule: For all i, A[i] <= B[i]. That is, A[i] can be any number you choose such that 1 <= A[i] <= B[i]. Your task is to select a series of A[i] given B[i] such that the sum of the absolute difference of consecutive pairs of A is maximized. This will be the array's cost, and will be represented by the variable S below.

The equation can be written:
  S = (E^N )i=2 |A[i]-A[i-1]|

For example, if the array B = [1, 2, 3], we know that 1 <= A[1] <= 1, 1 <= A[2] <= 2, and 1 <= A[3] <= 3. Arrays meeting those guidelines are:

[1,1,1], [1,1,2], [1,1,3]
[1,2,1], [1,2,2], [1,2,3]
Our calculations for the arrays are as follows:

|1-1| + |1-1| = 0	|1-1| + |2-1| = 1	|1-1| + |3-1| = 2
|2-1| + |1-2| = 2	|2-1| + |2-2| = 1	|2-1| + |3-2| = 2
The maximum value obtained is 2.

Function Description

Complete the cost function in the editor below. It should return the maximum value that can be obtained.

cost has the following parameter(s):

  B: an array of integers
Input Format

The first line contains the integer t, the number of test cases.

Each of the next t pairs of lines is a test case where:
- The first line contains an integer n, the length of B
- The next line contains n space-separated integers B[i]

Constraints

1 <= t <= 20
1 <= n <= 10^5
1 <= B[i] <= 100 

Output Format

For each test case, print the maximum sum on a separate line.



Solution :



title-img


                            Solution in C :

In C++ :






#include<math.h>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<stdio.h>
#include<map>
#include<ext/hash_map>
#include<ext/hash_set>
#include<set>
#include<string>
#include<assert.h>
#include<vector>
#include<time.h>
#include<queue>
#include<deque>
#include<sstream>
#include<stack>
#include<sstream>
#define MA(a,b) ((a)>(b)?(a):(b))
#define MI(a,b) ((a)<(b)?(a):(b))
#define AB(a) (-(a)<(a)?(a):-(a))
#define X first
#define Y second
#define mp make_pair
#define pb push_back
#define pob pop_back
#define ep 0.0000000001
#define pi 3.1415926535897932384626433832795

using namespace std;
using namespace __gnu_cxx;
const int N=1000111;
const int INF=1000000008;
int n,m,i,j,k,l,r,p;
int a[1000],b[1000];

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n;
        cin>>k;
        for (i=1;i<=k;i++) a[i]=0;
        for (i=k+1;i<=100;i++) a[i]=-INF;
        n--;
       //     for (i=1;i<=15;i++) cout<<a[i]<<" ";cout<<endl;
        while (n--)
        {
            scanf("%d",&k);
            p=-1;
            for (i=1;i<=k;i++)
            {
                p=MA(p+1,a[i]);
                b[i]=p;
            }
            p=-INF;
            for (i=100;i>=1;i--)
            {
                p=MA(p+1,a[i]);
                b[i]=MA(b[i],p);
            }
            for (j=k+1;j<=100;j++) b[j]=-INF;
            for (j=1;j<=100;j++) a[j]=b[j];
     //       for (i=1;i<=15;i++) cout<<a[i]<<" ";cout<<endl;
        }
    p=0;
    for (i=1;i<=k;i++) p=MA(p,a[i]);
    cout<<p<<endl;
    }
    return 0;
}








In Java :





import java.io.*;
import java.util.*;

public class Solution {

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;
	boolean eof;

	void solve() throws IOException {
		int n = nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}

		int dpLow = 0;
		int dpHigh = 0;

		for (int i = 1; i < n; i++) {
			int nextLow = Math.max(dpLow, dpHigh + a[i - 1] - 1);
			int nextHigh = Math.max(dpLow + a[i] - 1,
					dpHigh + Math.abs(a[i] - a[i - 1]));
			dpLow = nextLow;
			dpHigh = nextHigh;
			// System.err.println(dpLow + " " + dpHigh);
		}
		
		out.println(Math.max(dpLow, dpHigh));
	}

	Solution() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		int t = nextInt();
		while (t-- > 0) {
			solve();
		}
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new Solution();
	}

	String nextToken() {
		while (st == null || !st.hasMoreTokens()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				eof = true;
				return null;
			}
		}
		return st.nextToken();
	}

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			eof = true;
			return null;
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
}








In C :





#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main() {
    int T,N,B,L,R,ML,MR,X,Y,P,Q;
    scanf("%d",&T);
    for(int i = 0; i < T; i++) {
        scanf("%d",&N);
        for(int j = 0; j < N; j++) {
            scanf("%d",&B);
            if(j) {
                X = L - 1 + ML;
                Y = R - 1 + MR;
                P = abs(L - B) + ML;
                Q = abs(R - B) + MR;
                ML = (X > Y ? X : Y);
                MR = (P > Q ? P : Q);
            } else {
                ML = MR = 0;
            }
            L = 1;
            R = B;
        }
        printf("%d\n", (ML > MR ? ML : MR));
    }
    return 0;
}









In Python3 :





def cost(B) :
    c0,c1 = 0,0
    for i in range(1,len(B)) :
        c0,c1 = max(c0,c1+B[i-1]-1), max(c0+B[i]-1,c1+abs(B[i]-B[i-1]))
    return max(c0,c1)
    




T = int(input())

for _ in range(T) :
    N = int(input())
    B = [int(_) for _ in input().strip().split()]
    print(cost(B))
                        








View More Similar Problems

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →