Minimum Sum of a pair at least K distance apart from an Array

Given an array of integers A[] of size N, the task is to find the minimum sum that can be obtained by any pair of array elements which are at least K indices apart from each other.

Examples:

_Input: _A[] = {1, 2, 3, 4, 5, 6}, K = 2

_Output: _4

Explanation:

The minimum sum that can be obtained is by adding 1 and 3 that are at a distance of 2.

Input:_ A[] = {4, 2, 5, 4, 3, 2, 5}, K = 3_

Output:_ 4_

Explanation:

The minimum sum that can be obtained is by adding 2 and 2 that are at a distance of 4.

Naive Approach:

The simplest approach is to solve the problem is to iterate over the indices [i + K, N – 1] for every ith index and find the minimum element, say min. Check if min + A[i] is less than the minimum sum obtained so far and update minimum_sum accordingly. Finally, print the minimum_sum.

Below is the implementation of the above approach:

  • Java

// Java Program to implement

// the above approach

**import** java.util.*;

**class** GFG {

// Function to find the minimum

// sum of two elements that

// are atleast K distance apart

**public** **static** **void**

findMinSum(``**int** A[], **int** K)

{

// Length of the array

**int** n = A.length;

**int** minimum_sum

= Integer.MAX_VALUE;

// Iterate over the array

**for** (``**int** i = 0``; i < n; i++) {

// Initialize the min value

**int** min = Integer.MAX_VALUE;

// Iterate from i + k to N

**for** (``**int** j = i + K; j < n; j++)

// Find the minimum

min = Math.min(min, A[j]);

**if** (min == Integer.MAX_VALUE)

**continue**``;

// Update the minimum sum

minimum_sum = Math.min(minimum_sum,

A[i] + min);

}

// Print the answer

System.out.println(minimum_sum);

}

// Driver Code

**public** **static** **void**

main(String[] args)

{

**int** A[] = { 4``, 2``, 5``, 4``, 3``, 2``, 5 };

**int** K = 3``;

findMinSum(A, K);

}

}

Output:

4

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach:

The above approach can be optimized using a Suffix Array. Follow the steps below:

  • Initialize a suffix array(say suffix[]), where suffix[i] stores the minimum of all the elements from index N-1 to i.
  • For any ith index, the minimum element which is K distance apart is stored at index i + K in the suffix array.
  • For i ranging from 0 to N – 1, check if A[i] + suffix[i + k] < minimum_sum or not and update minimum_sum accordingly.
  • Finally, print minimum_sum as the required answer.

Below is the implementation of the above approach:

  • Java

// Java Program to implement

// the above approach

**import** java.util.*;

**class** GFG {

// Function to find the minimum

// sum of two elements that

// are atleast K distance apart

**public** **static** **void**

findMinSum(``**int** A[], **int** K)

{

// Length of the array

**int** n = A.length;

**int** suffix_min[] = **new** **int**``[n];

suffix_min[n - 1``] = A[n - 1``];

// Find the suffix array

**for** (``**int** i = n - 2``; i >= 0``; i--)

suffix_min[i]

= Math.min(suffix_min[i + 1``],

A[i]);

**int** min_sum = Integer.MAX_VALUE;

// Iterate in the array

**for** (``**int** i = 0``; i < n; i++) {

**if** (i + K < n)

// Update minimum sum

min_sum = Math.min(

min_sum, A[i]

+ suffix_min[i + K]);

}

// Print the answer

System.out.println(min_sum);

}

// Driver Code

**public** **static** **void** main(String[] args)

{

**int** A[] = { 1``, 2``, 3``, 4``, 5``, 6 };

**int** K = 2``;

findMinSum(A, K);

}

}

Output:

4

_Time Complexity: _O(N)

_Auxiliary Space: _O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #searching #suffix-array

What is GEEK

Buddha Community

Minimum Sum of a pair at least K distance apart from an Array
Mike  Kozey

Mike Kozey

1655243220

A Weather_widget Used for Flutter with Many Custom Config

weather_widget

Simple weather related widget, which can be freely combined to form a variety of weather backgrounds

Getting Started

depend

Add this to your package's pubspec.yaml file:

dependencies:
  weather_widget: ^1.0.6

Weatherwidget is easy to use, just add weatherwidget to start using

WeatherWidget(
             size:Size.infinite,
             weather:'Sunny',
             sunConfig:SunConfig()
         ),   

This will add a sunny day using the default settings
sunny
or other weather type
(Note: Raindrops and snowflakes need to specify the default number, and they will move randomly within the range)

WeatherWidget(
             size:Size.infinite,
             weather:'Cloudy',
             cloudConfig:CloudConfig()
         ),

WeatherWidget(
             size:Size.infinite,
             weather:'Rainy',
             rainConfig:RainConfig(
              rainNum:'the num of raindrops you want' 
             )
         ),


WeatherWidget(
             size:Size.infinite,
             weather:'Snowy',
             snowConfig:SnowConfig(
              snowNum:'the num of snowflakes you want' 
             )
         ),


WeatherWidget(
             size:Size.infinite,
             weather:'Thunder',
             thunderConfig:ThunderConfig()
         ),

rainy snowy thunder

Of course, each config contains other settings, such as the range, size, length, falling speed and color of random raindrops. You can use them to create hailstones and other weather features
If the default weather is not enough, you can use individual widgets and stack() widget to piece together the desired weather
Like this sunset breeze, etc
sunset breeze snow with rain thunder with rain
These are include in this widget
background

    BackgroundWidget(List<Color>,size)

cloud

    CloudWidget (Color)

A single random raindrop

RainWidget (
                         @required rainRangeXStart, #X-axis starting point of raindrop random occurrence
                         @required rainRangeXEnd,  
                         @required rainRangeYStart,
                         @required rainRangeYEnd,
                         @required durationRangeStartMill,  #Minimum time to fall
                         @required durationRangeEndMill,    
                         rainLength,
                         rainWidth,
                         rainColor,
                         rainCurve  #Curve of falling animation
                         )

A single random snowflake

SnowWidget (
                         this.snowAreaXStart,  #X-axis starting point of snowflake random occurrence
                         this.snowAreaXEnd,    
                         this.snowWaveRangeMin,    #The minimum floating distance of snowflakes
                         this.snowWaveRangeMax,    
                         this.snowFallSecMin,  #Minimum time of snowflake falling
                         this.snowFallSecMax,  
                         this.snowWaveSecMin,  #Minimum time for snowflake to float
                         this.snowWaveSecMax,
                         this.snowSize,
                         this.snowColor,
                         this.snowAreaYStart,   #Y-axis point of snowflake occurrence
                         this.snowAreaYEnd,    
                         this.waveCurve,        #Floating animation curve
                         this.fadeCurve         #Vanish animation curve
)

A single flash

ThunderWidget (
                         this.flashMillStart,   #Minimum flashing time
                         this.flashMillEnd,     
                         this.pauseMillStart,   #Minimum interval time
                         this.pauseMillEnd,     
                         this.blurStyle,        #blur model
                         this.blurSigma,        
                         this.points,
                         this.color,
                         this.width
)

a single wind

WindWidget (
                        this.pauseMillStart,    #Minimum interval time
                        this.pauseMillEnd,     
                        this.windPositionY,     #Y-axis point of wind occurrence
                        this.windSlideMill,     #Passing time
                        this.windColor,
                        this.windWidth,
                        this.windSlideXEnd,     
                        this.windSlideXStart,   
                        this.windGap,           #line spacing in a wind
                        this.blurStyle,
                        this.blurSigma
)

Using sunny weather by set the WeatherWidget background config in a sunConfig()

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add weather_widget

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  weather_widget: ^1.0.6

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:weather_widget/WeatherWidget.dart';
import 'package:weather_widget/example/main.dart';

example/main.dart

import 'package:flutter/material.dart';
import 'package:weather_widget/WeatherWidget.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WeatherWidget(
          size: Size.infinite,
          weather: 'Thunder',
          thunderConfig:ThunderConfig(
            thunderWidth:12
          )
    )
    );
  }
}

chinese 中文README

Author: Carendule
Source Code: https://github.com/carendule/WeatherWidget 
License: View license

#flutter #dart #widget 

Minimum Sum of a pair at least K distance apart from an Array

Given an array of integers A[] of size N, the task is to find the minimum sum that can be obtained by any pair of array elements which are at least K indices apart from each other.

Examples:

_Input: _A[] = {1, 2, 3, 4, 5, 6}, K = 2

_Output: _4

Explanation:

The minimum sum that can be obtained is by adding 1 and 3 that are at a distance of 2.

Input:_ A[] = {4, 2, 5, 4, 3, 2, 5}, K = 3_

Output:_ 4_

Explanation:

The minimum sum that can be obtained is by adding 2 and 2 that are at a distance of 4.

Naive Approach:

The simplest approach is to solve the problem is to iterate over the indices [i + K, N – 1] for every ith index and find the minimum element, say min. Check if min + A[i] is less than the minimum sum obtained so far and update minimum_sum accordingly. Finally, print the minimum_sum.

Below is the implementation of the above approach:

  • Java

// Java Program to implement

// the above approach

**import** java.util.*;

**class** GFG {

// Function to find the minimum

// sum of two elements that

// are atleast K distance apart

**public** **static** **void**

findMinSum(``**int** A[], **int** K)

{

// Length of the array

**int** n = A.length;

**int** minimum_sum

= Integer.MAX_VALUE;

// Iterate over the array

**for** (``**int** i = 0``; i < n; i++) {

// Initialize the min value

**int** min = Integer.MAX_VALUE;

// Iterate from i + k to N

**for** (``**int** j = i + K; j < n; j++)

// Find the minimum

min = Math.min(min, A[j]);

**if** (min == Integer.MAX_VALUE)

**continue**``;

// Update the minimum sum

minimum_sum = Math.min(minimum_sum,

A[i] + min);

}

// Print the answer

System.out.println(minimum_sum);

}

// Driver Code

**public** **static** **void**

main(String[] args)

{

**int** A[] = { 4``, 2``, 5``, 4``, 3``, 2``, 5 };

**int** K = 3``;

findMinSum(A, K);

}

}

Output:

4

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach:

The above approach can be optimized using a Suffix Array. Follow the steps below:

  • Initialize a suffix array(say suffix[]), where suffix[i] stores the minimum of all the elements from index N-1 to i.
  • For any ith index, the minimum element which is K distance apart is stored at index i + K in the suffix array.
  • For i ranging from 0 to N – 1, check if A[i] + suffix[i + k] < minimum_sum or not and update minimum_sum accordingly.
  • Finally, print minimum_sum as the required answer.

Below is the implementation of the above approach:

  • Java

// Java Program to implement

// the above approach

**import** java.util.*;

**class** GFG {

// Function to find the minimum

// sum of two elements that

// are atleast K distance apart

**public** **static** **void**

findMinSum(``**int** A[], **int** K)

{

// Length of the array

**int** n = A.length;

**int** suffix_min[] = **new** **int**``[n];

suffix_min[n - 1``] = A[n - 1``];

// Find the suffix array

**for** (``**int** i = n - 2``; i >= 0``; i--)

suffix_min[i]

= Math.min(suffix_min[i + 1``],

A[i]);

**int** min_sum = Integer.MAX_VALUE;

// Iterate in the array

**for** (``**int** i = 0``; i < n; i++) {

**if** (i + K < n)

// Update minimum sum

min_sum = Math.min(

min_sum, A[i]

+ suffix_min[i + K]);

}

// Print the answer

System.out.println(min_sum);

}

// Driver Code

**public** **static** **void** main(String[] args)

{

**int** A[] = { 1``, 2``, 3``, 4``, 5``, 6 };

**int** K = 2``;

findMinSum(A, K);

}

}

Output:

4

_Time Complexity: _O(N)

_Auxiliary Space: _O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #searching #suffix-array

Find array elements equal to sum of any subarray of at least size 2

Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 5, 6}_

Output:_ 3, 5, 6_

Explanation:

The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectively.

Input:_ arr[] = {5, 6, 10, 1, 3, 4, 8, 16}_

Output:_ 4, 8, 16_

Explanation:

The elements 4, 8, 16 are equal to the sum of subarrays {1, 3}, {1, 3, 4}, {1, 3, 4, 8} respectively

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use prefix sum array to solve the given problem. Create a prefix[] array that stores the prefix sum of all its preceding elements for every index. Store the sum of all subarrays in a map and search if any array element is present in the map or not.

#arrays #hash #prefix-sum #subarray #subarray-sum

Find array elements equal to sum of any subarray of at least size 2

Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 5, 6}_

Output:_ 3, 5, 6_

Explanation:

The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectively.

Input:_ arr[] = {5, 6, 10, 1, 3, 4, 8, 16}_

Output:_ 4, 8, 16_

Explanation:

The elements 4, 8, 16 are equal to the sum of subarrays {1, 3}, {1, 3, 4}, {1, 3, 4, 8} respectively

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use prefix sum array to solve the given problem. Create a prefix[] array that stores the prefix sum of all its preceding elements for every index. Store the sum of all subarrays in a map and search if any array element is present in the map or not.

#arrays #hash #prefix-sum #subarray #subarray-sum

Alayna  Rippin

Alayna Rippin

1596962520

Queries to find the Lower Bound of K from Prefix Sum Array

Given an array A[ ] consisting of non-negative integers and matrix Q[ ][ ] consisting of queries of the following two types:

  • **(1, l, val): **Update A[l] to A[l] + val.
  • **(2, K): **Find the lower_bound of **K **in the prefix sum array of A[ ]. If the lower_bound does not exist print -1.

The task for each query of second type is to print the index of lower_bound of value K.

Examples:

_Input: __A[ ] = {1, 2, 3, 5, 8}, Q[ ][ ] = {{1, 0, 2}, {2, 5}, {1, 3, 5}} _

_Output: __1 _

Explanation:

Query 1: Update A[0] to A[0] + 2. Now A[ ] = {3, 2, 3, 5, 8}

_Query 2: lower_bound of K = 5 in the prefix sum array {3, 5, 8, 13, 21} is 5 and index = 1. _

Query 3: Update A[3] to A[3] + 5. Now A[ ] = {3, 2, 3, 10, 8}

_Input: __A[ ] = {4, 1, 12, 8, 20}, Q[ ] = {{2, 50}, {1, 3, 12}, {2, 50}} _

_Output: __-1 _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive approach:

The simplest approach is to firstly build a prefix sum array of given array A[ ], and for queries of Type 1, update values and recalculate the prefix sum. For query of Type 2, perform a Binary Search on the prefix sum array to find lower bound.

Time Complexity:_ O(Q*(N*logn))_

_Auxiliary Space: _O(N)

Efficient Approach:

The above approach can be optimized using Fenwick Tree. Using this Data Structure, the update queries in prefix sum array can be performed in logarithmic time.

Follow the steps below to solve the problem:

  • Construct the Prefix Sum Array using Fenwick Tree.
  • For queries of Type 1, while** l > 0**, add val to A[l] traverse to the parent node by adding least significant bit in l.
  • For queries of Type 2, perform the Binary Search on the Fenwick Tree to obtain the lower bound.
  • Whenever a prefix sum greater than **K appears, **store that **index **and traverse the left part of the Fenwick Tree. Otherwise, traverse the right part of the Fenwick Tree Now, perform Binary Search.
  • Finally, print the required index.

Below is the implementation of the above approach:

  • Java
  • C#

// Java program to implement

// the above appraoch

**import** java.util.*;

**import** java.io.*;

**class** GFG {

// Function to calculate and return

// the sum of arr[0..index]

**static** **int** getSum(``**int** BITree[],

**int** index)

{

**int** ans = 0``;

index += 1``;

// Traverse ancestors

// of BITree[index]

**while** (index > 0``) {

// Update the sum of current

// element of BIT to ans

ans += BITree[index];

// Update index to that

// of the parent node in

// getSum() view by

// subtracting LSB(Least

// Significant Bit)

index -= index & (-index);

}

**return** ans;

}

// Function to update the Binary Index

// Tree by replacing all ancestores of

// index by their respective sum with val

**static** **void** updateBIT(``**int** BITree[],

**int** n, **int** index, **int** val)

{

index = index + 1``;

// Traverse all ancestors

// and sum with 'val'.

**while** (index <= n) {

// Add 'val' to current

// node of BIT

BITree[index] += val;

// Update index to that

// of the parent node in

// updateBit() view by

// adding LSB(Least

// Significant Bit)

index += index & (-index);

}

}

// Function to construct the Binary

// Indexed Tree for the given array

**static** **int**``[] constructBITree(

**int** arr[], **int** n)

{

// Initialize the

// Binary Indexed Tree

**int**``[] BITree = **new** **int**``[n + 1``];

**for** (``**int** i = 0``; i <= n; i++)

BITree[i] = 0``;

// Store the actual values in

// BITree[] using update()

**for** (``**int** i = 0``; i < n; i++)

updateBIT(BITree, n, i, arr[i]);

**return** BITree;

}

// Function to obtian and return

// the index of lower_bound of k

**static** **int** getLowerBound(``**int** BITree[],

**int**``[] arr, **int** n, **int** k)

{

**int** lb = -``1``;

**int** l = 0``, r = n - 1``;

**while** (l <= r) {

**int** mid = l + (r - l) / 2``;

**if** (getSum(BITree, mid) >= k) {

r = mid - 1``;

lb = mid;

}

**else**

l = mid + 1``;

}

**return** lb;

}

**static** **void** performQueries(``**int** A[], **int** n, **int** q[][])

{

// Store the Binary Indexed Tree

**int**``[] BITree = constructBITree(A, n);

// Solve each query in Q

**for** (``**int** i = 0``; i < q.length; i++) {

**int** id = q[i][``0``];

**if** (id == 1``) {

**int** idx = q[i][``1``];

**int** val = q[i][``2``];

A[idx] += val;

// Update the values of all

// ancestors of idx

updateBIT(BITree, n, idx, val);

}

**else** {

**int** k = q[i][``1``];

**int** lb = getLowerBound(

BITree, A, n, k);

System.out.println(lb);

}

}

}

// Driver Code

**public** **static** **void** main(String[] args)

{

**int** A[] = { 1``, 2``, 3``, 5``, 8 };

**int** n = A.length;

**int**``[][] q = { { 1``, 0``, 2 },

{ 2``, 5 },

{ 1``, 3``, 5 } };

performQueries(A, n, q);

}

}

Output:

1

Time Complexity:_ O(Q*(logN)2)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #bit magic #mathematical #searching #array-range-queries #bit #prefix-sum