the aluminium 2014 gives me wrong answer [3 , 9 , -6 , 7 ,-3 , 9 , -6 , -10] got 25 expected 28
but when i repeated the challenge with the same code and make case test it gives me the correct answer
Your test case [3, 9, -6, 7, -3, 9, -6, -10] : NO RUNTIME ERRORS (returned value: 28)
what is the wrong with it ???
the challenge :-
A non-empty zero-indexed array A consisting of N integers is given. A
pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of
array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ...
+ A[Q]. The maximum sum is the maximum sum of any slice of A. For example, consider array A such that: A[0] = 3
A[1] = 2
A[2] = -6
A[3] = 3
A[4] = 1 For example (0, 1) is a slice of A that has sum A[0] + A[1] = 5. This is the maximum sum of A. You can perform a single swap
operation in array A. This operation takes two indices I and J, such
that 0 ≤ I ≤ J < N, and exchanges the values of A[I] and A[J]. To goal
is to find the maximum sum you can achieve after performing a single
swap. For example, after swapping elements 2 and 4, you will get the
following array A: A[0] = 3
A[1] = 2
A[2] = 1
A[3] = 3
A[4] = -6 After that, (0, 3) is a slice of A that has the sum A[0] + A[1] + A[2] + A[3] = 9. This is the maximum sum of A after a single swap. Write a function: class Solution { public int solution(int[] A);
} that, given a non-empty zero-indexed array A of N integers, returns
the maximum sum of any slice of A after a single swap operation. For
example, given: A[0] = 3
A[1] = 2
A[2] = -6
A[3] = 3
A[4] = 1 the function should return 9, as explained above.
and my code is :-
import java.math.*;
class Solution {
public int solution(int[] A) {
if(A.length == 1)
return A[0];
else if (A.length==2)
return A[0]+A[1];
else{
int finalMaxSum = A[0];
for (int l=0 ; l<A.length ; l++){
for (int k = l+1 ; k<A.length ; k++ ){
int [] newA = A;
int temp = newA[l];
newA [l] = newA[k];
newA[k]=temp;
int maxSum = newA[0];
int current_max = newA[0];
for(int i = 1; i < newA.length; i++)
{
current_max = Math.max(A[i], current_max + newA[i]);
maxSum = Math.max(maxSum, current_max);
}
finalMaxSum = Math.max(finalMaxSum , maxSum);
}
}
return finalMaxSum;
}
}
}
i don't know what's the wrong with it ??
It was a bug in the website and this is the reply from the support team
the evaluation system run your program not only on the test case it presented to you, but also on the mirrored test case B = [-10, -6, 9, -3, 7, -6, 9, 3]. On test case B your program indeed returned 22, when it should have returned 28.
public static int findMaxSumOfArray(int[] A) {
int[] T = new int[A.length];
int sum = 0;
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;
int max1index = 0;
int max2intex = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] < 0) {
T[i] = sum;
sum = 0;
} else if (i == A.length - 1) {
sum += A[i];
T[i] = sum;
sum = 0;
} else {
sum += A[i];
}
}
for (int i = 0; i < T.length; i++) {
if (max3 < T[i]) {
if (max2 < T[i]) {
if (max1 < T[i]) {
max2intex = max1index;
max3 = max2;
max2 = max1;
max1 = T[i];
max1index = i;
} else {
max3 = max2;
max2 = T[i];
max2intex = i;
}
} else {
max3 = T[i];
}
}
}
return max1 + max2 + (Math.abs(max1index - max2intex) == 1 ? max3 : 0);
}
Related
I had one leetcode challenge, details are below.
Check If Array Pairs Are Divisible by k
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
Some basic use case above to evaluate the result.
My Implementation
import java.util.ArrayList;
class Solution {
public static boolean canArrange (int[]arr, int k)
{
if(arr.length % 2 != 0){
return false;
}
int pairs = arr.length / 2;
int[] firstPair = new int[pairs];
int[] secondPair = new int[pairs];
int n =0;
for(int i=0; i<arr.length;i++){
if(i < pairs){
firstPair[i] = arr[i];
}else{
secondPair[n] = arr[i];
n++;
}
}
System.out.println ("pairs =" + pairs);
int divisablePairs = 0;
ArrayList<Integer> firstElement = new ArrayList();
ArrayList<Integer> secondElement = new ArrayList();
for (int i = 0; i < firstPair.length; i++)
{
for (int j = 0; j < secondPair.length; j++)
{
if ((firstPair[i] + secondPair[j]) % k == 0 && (firstPair[i] + secondPair[j]) >= 0)
{
firstElement.add(firstPair[i]);
secondElement.add(secondPair[j]);
System.out.println ("(" + firstPair[i] + "," + secondPair[j] + ")");
divisablePairs++;
}
}
}
return divisablePairs > 0 ? true : false;
}
}
Here one particular use case is getting failed but I am not sure why. Use case give below.
Input:
Array - [9606,4830,4037,-1054,3308,6966,6528,3953,473,-388,9878,-3797,2598,-3283,5813,-6446,-3625,-107,-8756,-3053,-2131,6609,4192,7408,1115,7456,-5674,1219,-8548,540,-9630,-4858,-2453,-726,9902,6192,-7996,1459,-1980,4285,-2659,4156,-2303,-855]
K - 10
My Output:
true
Expected:
false
Someone explain what is the issue with my implementation?
Here we can use an integer map of k size.
This'll pass through:
public class Solution {
public static boolean canArrange(int[] arr, int k) {
int[] countMapRemainders = new int[k];
for (int a : arr) {
int remainder = a % k;
if (remainder < 0) {
remainder += k;
}
countMapRemainders[remainder]++;
}
for (int i = 1; i < k; i++) {
if (countMapRemainders[i] != countMapRemainders[k - i]) {
return false;
}
}
return countMapRemainders[0] % 2 == 0;
}
}
Inputs:
[1,2,3,4,5,10,6,7,8,9]
5
[9606,4830,4037,-1054,3308,6966,6528,3953,473,-388,9878,-3797,2598,-3283,5813,-6446,-3625,-107,-8756,-3053,-2131,6609,4192,7408,1115,7456,-5674,1219,-8548,540,-9630,-4858,-2453,-726,9902,6192,-7996,1459,-1980,4285,-2659,4156,-2303,-855]
10
Outputs:
true
false
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
You are given a sequence of N integers A denoted by A[1] , A[2]…..A[N].
Each integer in the sequence has a value associated with it W[1],W[2]…. W[N].
You have to select a subsequence of given array A such that all the elements in A are in strictly increasing order and sum of values of elements in this selected subsequence is maximum. You have to print this maximum value.
Sample Input
2
4
1 2 3 4
100 200 300 400
3
4 2 3
100 30 20
Sample Output
1000
100
I tried to solve this problem using dynamic programming but the time complexity of my code is n^2 so i want to reduce its complexity to nlogn can you help me?
Here is my implementation:
public class testing {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
int n = scn.nextInt();
int a[] = new int[n];
long val[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = scn.nextInt();
}
for (int i = 0; i < n; i++) {
val[i] = scn.nextLong();
}
long dp[] = new long[n];
Arrays.fill(dp, Integer.MIN_VALUE);
dp[0] = val[0];
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (a[j] < a[i]) {
dp[i] = Math.max(dp[i], dp[j] + val[i]);
}
}
}
long ans = Integer.MIN_VALUE;
for (long v : dp) {
ans = Math.max(v, ans);
}
sb.append(ans + "\n");
}
System.out.println(sb);
}
}
I am getting TLE because of contraints
Constraints
1 <= T <= 5 1 <= N <= 200000 1 <= a[i] <= 10^9, where i ∈ [1..N] 1 <= w[i] <= 10^9, where i ∈ [1..N]
Iterate once, and maintain a TreeMap of the sum of W values for A values less than or equal to the given A, as seen at the time you iterated over the A value.
For a new A, call the lowerEntry(key) method for the sum of W's below that new A.
Remember the largest sum, and return that.
Single iteration is O(n), and TreeMap use is O(log n), so solution is O(n log n)*.
static int sumIncreasing(int[] a, int[] w) {
int maxSum = Integer.MIN_VALUE;
TreeMap<Integer, Integer> sums = new TreeMap<>();
for (int i = 0; i < a.length; i++) {
Entry<Integer, Integer> lowerSum = sums.lowerEntry(a[i]);
int sum = (lowerSum != null ? lowerSum.getValue() + w[i] : w[i]);
sums.put(a[i], sum);
for (Entry<Integer, Integer> e; (e = sums.higherEntry(a[i])) != null && e.getValue() <= sum; )
sums.remove(e.getKey());
if (sum > maxSum)
maxSum = sum;
}
return maxSum;
}
*) The inner for loop is O(log n) (amortized, worst case), so it doesn't affect overall complexity.
Test
System.out.println(sumIncreasing(new int[] {1, 2, 3, 4}, new int[] {100, 200, 300, 400}));
System.out.println(sumIncreasing(new int[] {4, 2, 3}, new int[] {100, 30, 20}));
Output
1000
100
I just took this sample test, and it's right for the most part, but I am not sure why I would get the two cases wrong.
A non-empty zero-indexed array A consisting of N integers is given.
Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two
non-empty parts: A[0], A1, ..., A[P − 1] and A[P], A[P + 1], ...,
A[N − 1].
The difference between the two parts is the value of: |(A[0] + A1 +
... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the
first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3 A1 = 1 A[2] = 2 A[3] = 4 A[4] = 3 We can split
this tape in four places:
P = 1, difference = |3 − 10| = 7 P = 2, difference = |4 − 9| = 5 P =
3, difference = |6 − 7| = 1 P = 4, difference = |10 − 3| = 7 Write a
function:
class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A of N integers, returns
the minimal difference that can be achieved.
For example, given:
A[0] = 3 A1 = 1 A[2] = 2 A[3] = 4 A[4] = 3 the function
should return 1, as explained above.
Assume that:
N is an integer within the range [2..100,000]; each element of array A
is an integer within the range [−1,000..1,000]. Complexity:
expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N), beyond input storage (not counting the storage
required for input arguments).
class Solution {
public int solution(int[] A) {
int sum = 0;
int subtracted = 0;
int minDiff = 100000;
for (int i = 0; i < A.length; i++) {
sum += A[i];
}
for (int i = 0; i < A.length; i++) {
sum -= A[i];
subtracted += A[i];
int diff = (Math.abs(sum - subtracted));
if (minDiff > diff) {
minDiff = diff;
}
}
return minDiff;
}
}
Coldility Result
I wrote in java and achieved 100% on codility
public static int solution(int[] A) {
int sum=0,leftsum=0,rightsum=0,newmin=0,min=0;
for(int i=0;i<A.length;i++){
sum=sum+A[i];
}
for(int i=1;i<A.length;i++){
leftsum=leftsum+A[i-1];
rightsum=sum-leftsum;
//System.out.println(leftsum-rightsum);
if(i==1)
min=newmin=Math.abs(leftsum-rightsum);
else
newmin=Math.abs(leftsum-rightsum);
min=Math.min(min,newmin);
}
return min;
}
Consider this approach using just one for loop: The main idea is to accumulate from left and right at the same time until they cross the middle of the array. At that point, they will start sharing elements in the sum, so you need then to evaluate 2 cases:
1st- subtracting the shared elements from the left side
2nd- subtracting the shared elements from the right side
public int solution(int[] A) {
// write your code in C# 6.0 with .NET 4.5 (Mono)
int l=A.Length;
int mid= l%2>0 ? (l/2) : (l/2)-1;
long ls=0;
long rs=0;
long res=long.MaxValue;
long shared=0;
for(int i=0, j=l-1; i<l; i++, j--){
ls=ls+A[i];
rs=rs+A[j];
if(i>=mid && i<l-1){
if(i==j) shared=A[i];
else if(i>j) shared=shared+A[i]+A[j];
rs=rs-shared;
res= res < Math.Abs(ls-rs) ? res : Math.Abs(ls-rs);
rs=rs+shared;
ls=ls-shared;
res= res < Math.Abs(ls-rs) ? res : Math.Abs(ls-rs);
ls=ls+shared;
}
}
return (int)res;
}
Solved it. Don't use int sum = Arrays.stream(A).sum();, it fails the performance tests. I got all test case right except one with int sum = Arrays.stream(A).sum(); but it timed out on the largest test case. So I changed it to a for loop sum and it passed with 100%.
public int solution(int[] A) {
int result = Integer.MAX_VALUE;
int total = 0;
int sum = 0;
for (int i = 0; i < A.length; i++) {
sum += A[i];
}
for (int i = 0; i < A.length - 1; i++) {
total += A[i];
int toEndSum = sum - total;
int diff = Math.abs(total - toEndSum);
if (diff < result)
result = diff;
}
return result != Integer.MAX_VALUE ? result : 0;
}
this question is related to this post: https://stackoverflow.com/a/35810542/5888956
Basically, I have to write a program that reads in the integer from the keyboard, and it has to be able to display 50! using only array. (cannot use Biginteger or anything)
I got this so far, thanks to the help from the previous post.
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
int n;
Scanner kb = new Scanner(System.in);
System.out.println("Enter n");
n = kb.nextInt();
int [] result = fact(n);
int i = result.length-1;
while (i > 0 && result[i] == 0)
{
i--;
}
System.out.print(n + "! = ");
while (i >= 0)
{
System.out.print(result[i--]);
}
System.out.println();
}
public static int[] fact(int n)
{
int[] a = new int[100];
a[0] = 1;
for (int i = 1; i <= n; i++)
{
int carry = 0;
for(int j = 0; j < a.length; j++)
{
int x = a[j] * i + carry;
a[j] = x % 10;
carry = x / 10;
}
}
return a;
}
}
But I can't still understand the logic behind here.
Especially, this part,
for (int i = 1; i <= n; i++)
{
int carry = 0;
for(int j = 0; j < a.length; j++)
{
int x = a[j] * i + carry;
a[j] = x % 10;
carry = x / 10;
}
}
I'm trying to solve this with pen and paper, so that I can understand it completely. (of course with the small number like 4!)
So if I type 4 for n, 4! is 24 (4*3*2*1).
In my logic, when i is 1 a[0] is 1 because I initialized above, but after the for loop ends once, does it become 0?
i = 1, j = 0
x = a[0] * 1 + 0 = 1
a[0] = 0
carry = 1
// ------repeat the loop
i = 2, j = 0
x = a[0] * 1 + 1 = 1
a[0] = 0
carry = 1
So it is apparently not the right logic, I think.
Can someone please please help me to understand this?
The factorial operation just means multiplying a whole bunch of numbers, so conceptually, it is not a difficult operation to implement. The reason why it quickly becomes a problem when implementing in code, is that it produces huge numbers, in fact, too large to be held in one int (4 bytes) or even long (8 bytes) variables (12! is the max you could hold in an int). Otherwise, we would just do something like:
int fact = 1;
for(int i = 2 ; i <= n ; i++) {
fact *= i;
}
So one way to deal with this is to treat a number as an "array of digits", in base 10. For example, the number 2016 could be treated like this array: int[] digits = {2, 0, 1, 6}, which is just another way of saying 2016 = 2*1000 + 0*100 + 1*10 + 6*1.
Now let's imagine that we have 8-bits computers, and we can't represent numbers larger than 255 (or pow(2,8)-1). We wouldn't be able to simply do 2016*2 directly, but, because multiplication is distributive a(b+c) = ab+ac, we could decompose the multiplication of the "large" number 2016 into smaller multiplications like so:
2016 → {2, 0, 1, 6} → 2*1000 + 0*100 + 1*10 + 6
2016 * 2 = (2*1000 + 0 + 1*10 + 6) * 2 = (2*2)*1000 + (2*0) + (2*1)*10 + (2*6)
Now we can do these small multiplications like you would by hand:
2016 * 2 → {2, 0, 1, 6} * 2 → {2*2, 0*2, 1*2, 6*2} → {4, 0, 2, 12}
We get 12 for the first digit, so we need the carry over the 1:
{4, 0, 2, 12} → {4, 0, 2+1, 2} → {4, 0, 3, 2} = 4032
That's exactly what your code does:
a[0] = 1;
for (int i = 1; i <= n; i++) {
int carry = 0;
for(int j = 0; j < a.length; j++) {
int x = a[j] * i + carry;
a[j] = x % 10;
carry = x / 10;
}
}
It takes your number or "array of digits" a, and multiplies the digits a[j] individually by i → x = a[j] * i. If it's bigger than 9, take the extra to carry it to the next digit → carry = x / 10, and you're left with the remnant as the value of the digit → a[j] = x % 10.
`I have following array {9, 0, 2, -5, 7} and from this array i need to find the the square pairs <2, 7> and <7, 9> where first element must be less than second.
And <-5, 9> and <0, 9> are not square pairs, even though they sum to perfect squares,
because both members of a square pair have to be greater than 0.
bool ans;
int[] number = new int[]{9,0,2,-5,7};
for (int j = 0; j < number.Length; j++)
{
if (number[j]<number[j+1])
ans = IsPerfectSquares(number[j]+number[j+1]);
if(ans)
count++;
}
}
public static bool IsPerfectSquares(int input)
{ long SquareRoot = (long)Math.Sqrt(input);
return ((SquareRoot * SquareRoot) == input);
} `
C# Linq:
int[] array = {9, 0, 2, -5, 7};
int len = array.Length;
var pairs =
from i in Enumerable.Range(0, len-1)
where array[i] > 0
from j in Enumerable.Range(i+1, len-i-1)
where array[j] > 0
let sqrt = (int)Math.Sqrt(array[i] + array[j])
where array[i] + array[j] == sqrt * sqrt
select new {
A = Math.Min(array[i], array[j]),
B = Math.Max(array[i], array[j])
};
//or: select new int[] { ... };
Results:
{ A = 7, B = 9 }
{ A = 2, B = 7 }
Java: (also works in C# with slightly different syntax)
int[] array = { 9, 0, 2, -5, 7 };
List<int[]> pairs = new ArrayList<int[]>();
for (int i = 0; i < array.length - 1; ++i) {
if (array[i] <= 0) continue;
for (int j = i + 1; j < array.length; ++j) {
if (array[j] <= 0) continue;
int sqrt = (int)Math.sqrt(array[i] + array[j]);
if (array[i] + array[j] == sqrt * sqrt)
pairs.add(new int[] { array[i], array[j] });
}
}
I will let you write the code.
The algorithm is roughly this:
Iterate over the array. Remove all elements whose value is less than or equal to zero.
Create all possible pairs by using nested loop (two loops). For each pair, take the sum. Let say the sum is S. Take the square root of S. Let say the square root of R. Note that S is an integer (so, it may not exactly the square root of S). Check whether S is a perfect square by checking whether R*R = S.