Check if Array sum can be made equal to X using K triplet increment operations
Given an array arr of length N and two integers K and X. For every element arri in the array, if arri > 0 then the elements which are adjacent to it and the element itself will get incremented by 2 for all 1≤i≤N. Check if the sum of all array elements after performing the K operation is equal to X or not.
Examples:
Input: arr[] = { 0, 0, 1, 0, 0, 3 }, K = 2, X = 36
Output: True
Explanation: Initially arr[ ] = { 0, 0, 1, 0, 0, 3 }
After one operation array will be arr [ ] = { 0, 2, 3, 4, 4, 5 }
after Second times array will be arr [ ] = { 2, 4, 7, 8, 8, 7 }
Thus, sum of array is 36 which is equal to XInput: arr[ ] = {10, 6, 12, 8, 10, 8}, K = 2, X = 25
Output: False
Approach: This problem can be solved using brute force hit and trial technique:
- Traverse the given array
- For every index, increment the value at that index and its adjacent index by 2, except for the first and last element because they have only one element adjacent to them.
- Repeat the operations for every possibility in given array till array sum becomes at most X
- If after K operations, in any possibility, the array sum becomes X, return true.
- Else return false, if no such possibility exists.
Below is the implementation of the above approach:
C++
// C++ program to check whether sum// Is equal to target value// After K operations#include <bits/stdc++.h>using namespace std; // Function to chek sum of array// Value is equal to Targetbool find(int arr[], int N, int K, int Target){ while (K--) { for (int i = 0; i < N; i++) { // If it is first element just increment // next element if (arr[i] > 0 && i == 0) { arr[i + 1] = arr[i + 1] + 2; } // If it is last element just increment // Last second element else if (arr[i] > 0 && i == N - 1) { arr[N - 2] = arr[N - 2] + 2; } // If it is not a first element // Or not a last element // Increment both adjecent value by 2 else if (arr[i] > 0) { arr[i - 1] = arr[i - 1] + 2; arr[i + 1] = arr[i + 1] + 2; } } } // Calculate sum after performing // k times opretion int ans = accumulate(arr, arr + N, 0); if (ans == Target) { return 1; } else { return 0; }}// Driver Codeint main(){ int arr[] = { 0, 0, 1, 0, 0, 3 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; int Target = 36; // function call cout << (find(arr, N, K, Target) ? "true" : "false"); return 0;} |
true
Time Complexity: O(N * K)
Auxiliary Space: O(1)


 (2).jpg)