Trends

Max distance between first and last indexed element in Binary String

Trending 1 year ago
beritaja.com

import java.io.*;

import java.lang.*;

import java.util.*;

class GFG {

    public fixed void main(String[] args)

        throws java.lang.Exception

    {

        int N = 6;

        int K = 6;

        String S = "010110";

        int Y[] = { 2, 1, 3, 3, 4, 5 };

        Max_Distance(N, K, S, Y);

    }

    static void Max_Distance(int N, int K, String S,

                             int[] Y)

    {

        char arr[] = S.toCharArray();

        int sum = 0;

        int max = 0;

        for (int j = 0; j < N - 1; j++) {

            if (arr[j] == arr[j + 1])

                sum = sum + 2;

            else

                sum = sum + 1;

        }

        for (int j = 0; j < K; j++) {

            int a = Y[j] - 1;

            if (a > 0) {

                if (arr[a] == arr[a - 1])

                    sum = sum - 1;

                else

                    sum = sum + 1;

            }

            if (a < N - 1)

                if (arr[a] == arr[a + 1])

                    sum = sum - 1;

                else

                    sum = sum + 1;

            max = sum > max ? sum : max;

            if (arr[a] == '1')

                arr[a] = '0';

            else

                arr[a] = '1';

        }

        System.out.println(max);

    }

}

Editor: Naga



Read other contents from Beritaja.com at
More Source
close