Skip to content

Commit

Permalink
Added for 7 Jan
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanmay-312 committed Jan 7, 2024
1 parent c6ef458 commit 45ab767
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 0 deletions.
81 changes: 81 additions & 0 deletions GeeksForGeeks/7-1-24/GFG.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//{ Driver Code Starts
import java.io.*;
import java.util.*;

class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {

String St[] = read.readLine().split(" ");

int N = Integer.parseInt(St[0]);
int K = Integer.parseInt(St[1]);

String S[] = read.readLine().split(" ");

int[] arr = new int[N];

for(int i=0 ; i<N ; i++)
arr[i] = Integer.parseInt(S[i]);

Solution ob = new Solution();
System.out.println(ob.splitArray(arr,N,K));
}
}
}
// } Driver Code Ends


class Solution
{
static int splitArray(int[] arr , int N, int K)
{
// code here
int low = Integer.MIN_VALUE;
int high = 0;

for (int num : arr)
{
low = Math.max(low, num);
high += num;
}

while (low < high)
{
int mid = low + (high - low) / 2;

if (isValid(arr, N, K, mid))
{
high = mid;
}
else
{
low = mid + 1;
}
}

return low;
}

static boolean isValid(int[] arr, int N, int K, int mid)
{
int count = 0;
int currSum = 0;

for (int i = 0; i < N; i++)
{
currSum += arr[i];
if (currSum > mid)
{
count++;
currSum = arr[i];
}
}

count++;
return count <= K;
}
};
2 changes: 2 additions & 0 deletions GeeksForGeeks/7-1-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(n * log(sum(arr))
Space complexity - O(1)
2 changes: 2 additions & 0 deletions LeetCode/7-1-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(n^2)
Space complexity - O(n^2)
33 changes: 33 additions & 0 deletions LeetCode/7-1-24/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution
{
public int numberOfArithmeticSlices(int[] nums)
{
final int n = nums.length;
int ans = 0;

// dp[i][j] := the number of subsequences end in nums[j] nums[i]
int[][] dp = new int[n][n];

Map<Long, List<Integer>> numToIndices = new HashMap<>();

for (int i = 0; i < n; ++i)
{
numToIndices.putIfAbsent((long) nums[i], new ArrayList<>());
numToIndices.get((long) nums[i]).add(i);
}

for (int i = 0; i < n; ++i)
for (int j = 0; j < i; ++j)
{
final long target = nums[j] * 2L - nums[i];
if (numToIndices.containsKey(target))
for (final int k : numToIndices.get(target))
if (k < j)
dp[i][j] += (dp[j][k] + 1);

ans += dp[i][j];
}

return ans;
}
}

0 comments on commit 45ab767

Please sign in to comment.