Sherlock and Array

Watson gives Sherlock an array of integers. His challenge is to find an element of the array such that the sum of all elements to the left is equal to the sum of all elements to the right. 

Example:

Input: n=4, arr[]={1,2,3,3}
Output: YES

Approach

Java


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SherlockArray {
    public static void main(String[] args) {
        int[] arr = { 1233 };
        String result = balancedSums(Arrays.stream(arr).
            boxed().collect(Collectors.toList()));
        System.out.println(result);
    }

    private static String balancedSums(List<Integerarr) {

        int n = arr.size();
        int left[] = new int[n];
        int right[] = new int[n];

        left[0] = 0;
        right[n - 1] = 0;
        for (int i = 1; i < n; i++)
            left[i] = left[i - 1] + arr.get(i - 1);
        for (int i = n - 2; i >= 0; i--)
            right[i] = right[i + 1] + arr.get(i + 1);
        int i = 0;
        while (i < n) {
            if (left[i] == right[i])
                return "YES";
            else
                i++;
        }
        return "NO";
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

string balancedSums(vector<intarr)
{
    int n = arr.size();
    int *left = (int *)malloc(sizeof(int) * n);
    int *right = (int *)malloc(sizeof(int) * n);

    left[0] = 0;
    right[n - 1] = 0;
    for (int i = 1i < ni++)
        left[i] = left[i - 1] + arr[i - 1];
    for (int i = n - 2i >= 0i--)
        right[i] = right[i + 1] + arr[i + 1];
    int i = 0;
    while (i < n)
    {
        if (left[i] == right[i])
            return "YES";
        else
            i++;
    }
    return "NO";
}

int main()
{

    int n = 4;
    vector<intarr = {1233};

    string result = balancedSums(arr);
    cout << result << "\n";

    return 0;
}


No comments:

Post a Comment