Make sums of left and right sides of array equal by removing subarray

纵然是瞬间 提交于 2021-02-10 22:14:00

问题


C program that finds starting and ending indexes of subarray to remove to make given array have equal sums of left and right side. If its impossible print -1. I need it to work for any array, this is just for testing. Heres a code that finds equilibrium.

#include <stdio.h> 

int equilibrium(int arr[], int n) 
{ 
int i, j; 
int leftsum, rightsum; 

/* Check for indexes one by one until 
an equilibrium index is found */
for (i = 0; i < n; ++i) {    

    /* get left sum */
    leftsum = 0; 
    for (j = 0; j < i; j++) 
        leftsum += arr[j]; 

    /* get right sum */
    rightsum = 0; 
    for (j = i + 1; j < n; j++) 
        rightsum += arr[j]; 

    /* if leftsum and rightsum are same, 
    then we are done */
    if (leftsum == rightsum) 
        return i; 
} 

/* return -1 if no equilibrium index is found */
return -1; 
} 

// Driver code 
int main() 
{ 
int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; 
int arr_size = sizeof(arr) / sizeof(arr[0]); 
printf("%d", equilibrium(arr, arr_size)); 

getchar(); 
return 0; 
}

回答1:


You could solve this problem in O(NlogN) or O(N)(in average case).

First, you need to make a pre-processing, saving all the sums from right to left in a data structure, specifically a balanced binary search tree(e.g. Red Black tree, AVL Tree, Splay Tree, etc, if you could use stdlib, just use std::multiset) or a HashTable(in stdlib it's std::unordered_multiset):

void preProcessing(dataStructure & ds, int * arr, int n){
    int sum = 0;
    int * toDelete = (int) malloc(n)
    for(int i = n-1; i >= 0; --i){
        sum += arr[i];
        toDelete[i] = sum; // Save items to delete later.
        tree.insert(sum);
    }

So to solve problem you just need to traverse the array one time:

// It considers that the deleted subarray could be empty
bool Solve(dataStructure & ds, int * arr, int n, int * toDelete){
    int sum = 0;
    bool solved = false; // true if a solution is found
    for(int i = 0 ; i < n; ++i){ 
        ds.erase(toDelete[i]); // deletes the actual sum up to i-th element from data structure, as it couldn't be part of the solution.
                               // It costs O(logN)(BBST) or O(1)(Hashtable)
        sum += arr[i];
        if(ds.find(sum)){// If sum is in ds, then there's a leftsum == rightsum
                         // It costs O(logN)(BBST) or O(1)(HashTable)
            solved = true;
            break;
        }
    }
    return solved;
}

Then, if you use a BBST(Balanced Binary Search Tree) your solution would be O(NlogN), but, if you use HashTable, your solution would be O(N) on average. I wouldn't implemented it, so maybe there's a bug, but I try to explain the main idea.



来源:https://stackoverflow.com/questions/53900626/make-sums-of-left-and-right-sides-of-array-equal-by-removing-subarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!