minimum number of coins to make change - java

I am trying to print the minimum number of coins to make the change, if not possible print -1
In this code variable int[] c (coins array) has denominations I can use to come up with Total sum.
int total has total sum I need to come up with using coins (Unlimited supply)
public static int mincoinDP(int[] c, int total) {
int[][] a = new int[c.length + 1][total + 1];
for (int i = 0; i <= c.length; i++) {
a[i][0] = 0;
}
for (int j = 1; j <= total; j++) {
a[0][j] = Integer.MAX_VALUE - total;
}
for (int i = 1; i <= c.length; i++) {
for (int j = 1; j <= total; j++) {
if (c[i - 1] > j) {
a[i][j] = Integer.MAX_VALUE - total;
} else {
a[i][j] = Math.min(a[i - 1][j], 1 + a[i][j - c[i - 1]]);
}
}
}
return a[c.length][total];
}
For Sum : 4759 and Array: {31 90 8 36} Correct output is: 59
My output is: 60
What is wrong in code ?
Below is my recursive solution, trying to apply same logic in DP solution. Something seems to be wrong in logic here as well. For same input it prints -2147483595
public static void main(String[] args) {
int[] array = new int[] {31, 90, 8, 36};
System.out.println(mincoin(array, 4759, 0));
}
public static int mincoin(int[] c, int total, int i) {
if (total == 0) return 0;
if (i >= c.length) return Integer.MAX_VALUE;
int x = Integer.MAX_VALUE, y = Integer.MAX_VALUE;
if (total - c[i] >= 0) {
x = 1 + mincoin(c, total - c[i], i);
}
y = mincoin(c, total, i + 1);
return Math.min(x, y);
}
Edit: Problems in code were:
DP version: if (c[i -1] > j) , It is case when solution is not
possible choosing this coin: Here we should accept solution without
this coin which is a[i-1][j]
Recursive version: if(i >= c.length),
it is terminating condition when we dont any coin at this position,
here we should return infinity (Integer.MAX_VALUE) and
to avoid integer overflow return Integer.MAX_VALUE - total.
Though I dont like this version of infinity, but dont see any nice way other than this here.

It looks like you're using dynamic programming, with a[i][j] intended to represent the minimum number of coins (using the first i denominations) that sum to j. But I think your recurrence relations are off. They should be:
a[0][j] = 0 if j==0, otherwise infinity
a[i][j] = a[i-1][j] if c[i-1] > j
a[i][j] = min(a[i-1][j], 1 + a[i][j-c[i-1]]) if c[i-1] <= j
The main mistake is the if c[i-1] > j case in your code. You set the value to infinity (or your variant of infinity), but you should just copy the minimum number of coins from the previous row since you may be able to construct the total using the smaller number of coins.
By the way, there is a neater way to write this code. In pseudocode:
a = new int[total+1]
for int j = 1 to total+1 {
a[j] = infinity
}
for int coin in coins {
for j = coin to total+1 {
a[j] = min(a[j], a[j-coin]+1)
}
}
It's essentially the same algorithm, but it uses a smaller one-dimensional array which it modifies in-place.

Just in case someone looking for solution
public int coinChange(int[] coins, int amount) {
int dp[][] = new int[coins.length+1][amount+1];
Arrays.sort(coins);
// First column of every row
for (int i = 0; i < coins.length; ++i) {
dp[i][0] = 0;
}
/*
Setting this so that this is default max value. We always
want our dp[i][j] better than this
*/
for (int j = 0; j <= amount; ++j) {
dp[0][j] = amount+1;
}
for (int i = 1; i <= coins.length; ++i) {
for (int j = 1; j <= amount; ++j) {
if (coins[i-1] > j) {
dp[i][j] = dp[i-1][j]; // Take the already best value in above row
} else {
dp[i][j] = Math.min(dp[i-1][j], 1 + dp[i][j-coins[i-1]]); // Take the best of above row and using current coin
}
}
}
if (dp[coins.length][amount] > amount) { // it means we cannot find any coin
return -1;
} else {
return dp[coins.length][amount];
}
}

Related

How to reduce the number of loops if there is no change?

This code is radix sort in Java.
Now I can sort. But I want to reduce its functionality if there is no change in the
array, let it stop the loop and show the value.
Where do I have to fix it? Please guide me, thanks in advance.
public class RadixSort {
void countingSort(int inputArray[], int size, int place) {
//find largest element in input array at 'place'(unit,ten's etc)
int k = ((inputArray[0] / place) % 10);
for (int i = 1; i < size; i++) {
if (k < ((inputArray[i] / place) % 10)) {
k = ((inputArray[i] / place) % 10);
}
}
//initialize the count array of size (k+1) with all elements as 0.
int count[] = new int[k + 1];
for (int i = 0; i <= k; i++) {
count[i] = 0;
}
//Count the occurrence of each element of input array based on place value
//store the count at place value in count array.
for (int i = 0; i < size; i++) {
count[((inputArray[i] / place) % 10)]++;
}
//find cumulative(increased) sum in count array
for (int i = 1; i < (k + 1); i++) {
count[i] += count[i - 1];
}
//Store the elements from input array to output array using count array.
int outputArray[] = new int[size];
for (int j = (size - 1); j >= 0; j--) {
outputArray[count[((inputArray[j] / place) % 10)] - 1] = inputArray[j];
count[(inputArray[j] / place) % 10]--;//decrease count by one.
}
for (int i = 0; i < size; i++) {
inputArray[i] = outputArray[i];//copying output array to input array.
}
System.out.println(Arrays.toString(inputArray));
}
void radixSort(int inputArray[], int size) {
//find max element of inputArray
int max = inputArray[0];
for (int i = 1; i < size; i++) {
if (max < inputArray[i]) {
max = inputArray[i];
}
}
//find number of digits in max element
int d = 0;
while (max > 0) {
d++;
max /= 10;
}
//Use counting cort d no of times
int place = 1;//unit place
for (int i = 0; i < d; i++) {
System.out.print("iteration no = "+(i+1)+" ");
countingSort(inputArray, size, place);
place *= 10;//ten's , hundred's place etc
}
}
1
I'm going to resist typing out some code for you and instead go over the concepts since this looks like homework.
If I'm understanding you correctly, your problem boils down to: "I want to check if two arrays are equivalent and if they are, break out of a loop". Lets tackle the latter part first.
In Java, you can use the keyword"
break;
to break out of a loop.
A guide for checking if two arrays are equivalent in java can be found here:
https://www.geeksforgeeks.org/compare-two-arrays-java/
Sorry if this doesnt answer your question. Im just gonna suggest a faster way to find the digits of each element. Take the log base 10 of the element and add 1.
Like this : int digits = (int) Math.log10(i)+1;

Intuition for array in dynamic problem: coin change combinations

Coding Problem Link
i have coded the brute-force recursion without any DP.
public class coinChangeCombination {
public static void main(String[] args){
int[] coins = {2, 3, 5, 6};
int target = 7;
System.out.println(coinRecursive(0, target, coins, 0));
}
//basic recursion
public static int coinRecursive(int current, int target, int[] coins, int index){
if(current > target) return 0;
if(current == target) return 1;
int count = 0;
for(int i = index; i < coins.length; i++){
int res = coinRecursive(current+coins[i], target, coins, i);
count += res;
}
return count;
}
}
Now since two variables are getting changed in recursion, we will need a 2-d array to store the intermediate results but what does each cell of the 2-d array represent? Like in Fibonacci DP when we take a 1-d array, each cell represents the Fibonacci of that index, likewise what does our 2-d array in this question represent? i am unable to think the meaning behind it, whats the intuition?
A bottom-up approach for this coin changes problem in Java to demo the DP way:
class Solution {
public int change(int amount, int[] coins) {
int n = coins.length;
int[][] dp = new int[2][amount + 1];
for (int i = 0; i <= n; i++)
dp[i % 2][0] = 1; // one way to change 0 amount
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= amount; j++) {
dp[i % 2][j] = dp[(i - 1) % 2][j]; // skip ith coin
if (j >= coins[i - 1])
dp[i % 2][j] += dp[i % 2][j - coins[i - 1]]; // use ith coin
}
}
return dp[n % 2][amount];
}
}

Calculate factorial of 50 using array only in java

I'm a total beginner of java.
I have a homework to write a complete program that calculates the factorial of 50 using array.
I can't use any method like biginteger.
I can only use array because my professor wants us to understand the logic behind, I guess...
However, he didn't really teach us the detail of array, so I'm really confused here.
Basically, I'm trying to divide the big number and put it into array slot. So if the first array gets 235, I can divide it and extract the number and put it into one array slot. Then, put the remain next array slot. And repeat the process until I get the result (which is factorial of 50, and it's a huge number..)
I tried to understand what's the logic behind, but I really can't figure it out.. So far I have this on my mind.
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();
System.out.println(n +"! = " + fact(n));
}
public static int fact(int n)
{
int product = 1;
int[] a = new int[100];
a[0] = 1;
for (int j = 2; j < a.length; j++)
{
for(; n >= 1; n--)
{
product = product * n;
a[j-1] = n;
a[j] = a[j]/10;
a[j+1] = a[j]%10;
}
}
return product;
}
}
But it doesn't show me the factorial of 50.
it shows me 0 as the result, so apparently, it's not working.
I'm trying to use one method (fact()), but I'm not sure that's the right way to do.
My professor mentioned about using operator / and % to assign the number to the next slot of array repeatedly.
So I'm trying to use that for this homework.
Does anyone have an idea for this homework?
Please help me!
And sorry for the confusing instruction... I'm confused also, so please forgive me.
FYI: factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000
Try this.
static int[] fact(int n) {
int[] r = new int[100];
r[0] = 1;
for (int i = 1; i <= n; ++i) {
int carry = 0;
for (int j = 0; j < r.length; ++j) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
and
int[] result = fact(50);
int i = result.length - 1;
while (i > 0 && result[i] == 0)
--i;
while (i >= 0)
System.out.print(result[i--]);
System.out.println();
// -> 30414093201713378043612608166064768844377641568960512000000000000
Her's my result:
50 factorial - 30414093201713378043612608166064768844377641568960512000000000000
And here's the code. I hard coded an array of 100 digits. When printing, I skip the leading zeroes.
public class FactorialArray {
public static void main(String[] args) {
int n = 50;
System.out.print(n + " factorial - ");
int[] result = factorial(n);
boolean firstDigit = false;
for (int digit : result) {
if (digit > 0) {
firstDigit = true;
}
if (firstDigit) {
System.out.print(digit);
}
}
System.out.println();
}
private static int[] factorial(int n) {
int[] r = new int[100];
r[r.length - 1] = 1;
for (int i = 1; i <= n; i++) {
int carry = 0;
for (int j = r.length - 1; j >= 0; j--) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
}
How about:
public static BigInteger p(int numOfAllPerson) {
if (numOfAllPerson < 0) {
throw new IllegalArgumentException();
}
if (numOfAllPerson == 0) {
return BigInteger.ONE;
}
BigInteger retBigInt = BigInteger.ONE;
for (; numOfAllPerson > 0; numOfAllPerson--) {
retBigInt = retBigInt.multiply(BigInteger.valueOf(numOfAllPerson));
}
return retBigInt;
}
Please recall basic level of math how multiplication works?
2344
X 34
= (2344*4)*10^0 + (2344*3)*10^1 = ans
2344
X334
= (2344*4)*10^0 + (2344*3)*10^1 + (2344*3)*10^2= ans
So for m digits X n digits you need n list of string array.
Each time you multiply each digits with m. and store it.
After each step you will append 0,1,2,n-1 trailing zero(s) to that string.
Finally, sum all of n listed string. You know how to do that.
So up to this you know m*n
now it is very easy to compute 1*..........*49*50.
how about:
int[] arrayOfFifty = new int[50];
//populate the array with 1 to 50
for(int i = 1; i < 51; i++){
arrayOfFifty[i-1] = i;
}
//perform the factorial
long result = 1;
for(int i = 0; i < arrayOfFifty.length; i++){
result = arrayOfFifty[i] * result;
}
Did not test this. No idea how big the number is and if it would cause error due to the size of the number.
Updated. arrays use ".length" to measure the size.
I now updated result to long data type and it returns the following - which is obviously incorrect. This is a massive number and I'm not sure what your professor is trying to get at.
-3258495067890909184

Dynamic Programming (Codility Q: NumberSolitaire)

This is the question:
codility.com/programmers/task/number_solitaire
and below link is my result (50% from Codility):
https://codility.com/demo/results/training8AMJZH-RTA/
My code (at the first, I tried to solve this problem using Kadane's Algo):
class Solution {
public int solution(int[] A) {
int temp_max = Integer.MIN_VALUE;
int max = 0;
int k = 1;
if(A.length == 2) return A[0] + A[A.length-1];
for(int i = 1; i < A.length-1; i++) {
if(temp_max < A[i]) temp_max = A[i];
if(A[i] > 0) {
max += A[i];
temp_max = Integer.MIN_VALUE;
k = 0;
} else if(k % 6 == 0) {
max += temp_max;
temp_max = Integer.MIN_VALUE;
k = 0;
}
k++;
}
return A[0] + max + A[A.length-1];
}
And below is the solution (100% from Codility result) that I found from web:
class Solution {
public int solution(int[] A) {
int[] store = new int[A.length];
store[0] = A[0];
for (int i = 1; i < A.length; i++) {
store[i] = store[i-1];
for (int minus = 2; minus <= 6; minus++) {
if (i >= minus) {
store[i] = Math.max(store[i], store[i - minus]);
} else {
break;
}
}
store[i] += A[i];
}
return store[A.length - 1];
}
}
I have no idea what is the problem with my code:(
I tried several test cases but, nothing different with the solution & my code
but, codility test result shows mine is not perfectly correct.
(https://codility.com/demo/results/training8AMJZH-RTA/)
please anyone explain me the problem with my code~~
Try this test case[-1, -2, -3, -4, -3, -8, -5, -2, -3, -4, -5, -6, -1].
you solution return -4 (A[0],A[1],A[length-1],Here is the mistake), but the correct answer is -6 (A[0],A[6],A[length-1]).
Here is a my solution,easy to understand:
public int solution(int[] A) {
int lens = A.length;
int dp[] = new int[6];
for (int i = 0; i < 6; i++) {
dp[i] = A[0];
}
for (int i = 1; i < lens; i++) {
dp[i%6] = getMax6(dp) + A[i];
}
return dp[(lens-1)%6];
}
private int getMax6(int dp[]){
int max = dp[0];
for (int i = 1; i < dp.length; i++) {
max = Math.max(max, dp[i]);
}
return max;
}
Readable solution from Java:
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().solution(new int[]{1, -2, 0, 9, -1, -2}));
}
private int solution(int[] A) {
int N = A.length;
int[] dp = new int[N];
dp[0] = A[0];
for (int i = 1; i < N; i++) {
double sm = Double.NEGATIVE_INFINITY;
for (int j = 1; j <= 6; j++) {
if (i - j < 0) {
break;
}
double s1 = dp[i - j] + A[i];
sm = Double.max(s1, sm);
}
dp[i] = (int) sm;
}
return dp[N-1];
}
}
Here is a solution similar to #0xAliHn but using less memory. You only need to remember the last 6 moves.
def NumberSolitaire(A):
dp = [0] * 6
dp[-1] = A[0]
for i in range(1, len(A)):
maxVal = -100001
for k in range(1, 7):
if i-k >= 0:
maxVal = max(maxVal, dp[-k] + A[i])
dp.append(maxVal)
dp.pop(0)
return dp[-1]
Based on the solutions posted, I made nice readable code. Not best performance.
int[] mark = new int[A.length];
mark[0] = A[0];
IntStream.range(1, A.length)
.forEach(i -> {
int max = Integer.MIN_VALUE;
mark[i] = IntStream.rangeClosed(1, 6)
.filter(die -> i - die >= 0)
.map(r -> Math.max(mark[i - r] + A[i], max))
.max().orElse(max);
});
return mark[A.length - 1];
Because you are not using dynamic programming, you are using greedy algorithm. Your code will fail when the max number in a range will not be the right choice.
function solution(A) {
// This array contains a maximal value at any index.
const maxTill = [A[0]];
// It's a dynamic programming so we will choose maximal value at each
// Index untill we reach last index (goal)
for (let i = 1; i < A.length; i++) {
// Step 1 . max value of each index will be atleast equal to or greater than
// max value of last index.
maxTill[i] = maxTill[i - 1];
// For each index we are finding the max of last 6 array value
// And storing it into Max value.
for (let dice = 1; dice <= 6; dice++) {
// If array index is itself less than backtrack index
// break as you dont have 6 boxes in your left
if (dice > i) {
break;
} else {
// The most important line .
// Basically checking the max of last 6 boxes using a loop.
maxTill[i] = Math.max(
maxTill[i - dice],
maxTill[i]
);
}
}
// Until this point maxStill contains the maximal value
// to reach to that index.
// To end the game we need to touch that index as well, so
// add the value of the index as well.
maxTill[i] += A[i];
}
return maxTill[A.length - 1];
}
console.log(solution([-1, -2, -3, -4, -3, -8, -5, -2, -3, -4, -5, -6, -1]));
This is my solution. I try to make the code easy to apprehend. It might not save space as much as it can.
private static int solution(int A[])
{
// N // N is an integer within the range [2..100,000];
// A[] // each element of array A is an integer within the range [−10,000..10,000].
int N = A.length;
int[] bestResult = new int[N]; // record the current bestResult
Arrays.fill(bestResult, Integer.MIN_VALUE); // fill in with the smallest integer value
// initialize
bestResult[0] = A[0];
for (int i = 0;i < A.length;i++) {
// calculate six possible results every round
for (int j = i + 1; (j < A.length) && (i < A.length) && j < (i + 1) + 6; j++) {
// compare
int preMaxResult = bestResult[j]; // the max number so far
int nowMaxResult = bestResult[i] + A[j]; // the max number at bestResult[i] + A[j]
bestResult[j] = Math.max(preMaxResult, nowMaxResult);
}
}
return bestResult[bestResult.length-1];
}
Here is the simple Python 3 solution:
import sys
def solution(A):
dp = [0] * len(A)
dp[0] = A[0]
for i in range(1, len(A)):
maxVal = -sys.maxsize - 1
for k in range(1, 7):
if i-k >= 0:
maxVal = max(maxVal, dp[i-k] + A[i])
dp[i] = maxVal
return dp[len(A)-1]
100% c++ solution(
results)
#include <climits>
int solution(vector<int>& A) {
const int N = A.size();
if (N == 2)
return A[0] + A[1];
vector<int> MaxSum(N, INT_MIN);
MaxSum[0] = A[0];
for (int i = 1; i < N; i++) {
for (int dice = 1; dice <= 6; dice++) {
if (dice > i)
break;
MaxSum[i] = max(MaxSum[i], A[i] + MaxSum[i - dice]);
}
}
return MaxSum[N-1];
}
100% python solution
with the help of the answers above and https://sapy.medium.com/cracking-the-coding-interview-30eb419c4c57
def solution(A):
# write your code in Python 3.6
# initialize maxUntil [0]*n
n = len(A)
maxUntil = [0 for i in range(n)]
maxUntil[0]=A[0]
# fill in maxUntil, remember to chack limits
for i in range(1, n): # for each
maxUntil[i] = maxUntil [i-1]
# check the max 6 to the left:
# for 1,..,6:
for dice in range(1,7):
if dice > i: # if dice bigger than loc - we are out of range
break
#else: check if bigger than cur elem, if so - update elem
maxUntil[i] = max(maxUntil[i],maxUntil[i-dice])
# add the current jump:
maxUntil[i] +=A[i]
# must reach the last sq:
return maxUntil[n-1]
I would like to explain the algorithm I have come up with and then show you the implementation in C++.
Create a hash for the max sums. We only need to store the elements within reach, so the last 6 elements. This is because the dice can only go back so much.
Initialise the hash with the first element in the array for simplicity since the first element in this hash equals to the first element of the inputs.
Then go through the input elements from the second element.
For each iteration, find the maximum values from the last 6 indices. Add the current value to that to get the current max sum.
When we reach the end of the inputs, exit the loop.
Return the max sum of the last element calculated. For this, we need clipping with module due to the space optimisation
The runtime complexity of this dynamic programming solution is O(N) since we go through element in the inputs. If we consider the dice range K, then this would be O(N * K).
The space complexity is O(1) because we have a hash for the last six elements. It is O(K) if we does not consider the number of dice faces constant, but K.
int solution(vector<int> &A)
{
vector<int> max_sums(6, A[0]);
for (size_t i = 1; i < A.size(); ++i) max_sums[i % max_sums.size()] = *max_element(max_sums.cbegin(), max_sums.cend()) + A[i];
return max_sums[(A.size() - 1) % max_sums.size()];
}
Here's my answer which gives 100% for Kotlin
val pr = IntArray(A.size) { Int.MIN_VALUE }
pr[0] = A.first()
for ((index, value) in pr.withIndex()) {
for (i in index + 1..min(index + 6, A.lastIndex)) {
pr[i] = max(value + A[i], pr[i])
}
}
return pr.last()
I used forwarded prediction, where I fill the next 6 items of the max value the current index can give.

find second and third maximum element array java

I have to find 1st, 2nd, and 3rd largest array. I know I could simply sort it and return array[0], array[1], array[3]. But the problem is, i need the index, not the value.
For example if i have float[] listx={8.0, 3.0, 4.0, 5.0, 9.0} it should return 4, 0, and 3.
Here's the code I have but it doesn't work:
//declaration max1-3
public void maxar (float[] listx){
float maxel1=0;
float maxel2=0;
float maxel3=0;
for (int i=0; i<listx.length; i++){
if(maxel1<listx[i])
{maxel1=listx[i];
max1=i;
}
}
listx[max1]=0; //to exclude this one in nextsearch
for (int j=0; j<listx.length; j++){
if(listx[j]>maxel2)
{maxel2=listx[j];
max2=j;
}
}
listx[max2]=0;
for (int k=0; k<listx.length; k++){
if(listx[k]>maxel3)
{maxel3=listx[k];
max3=k;
}
}
}
I get max1 right but after that all the elements turns to 0. hence max2 and max3 become 0. Please suggest me what is wrong with this solution. Thank you.
You can find the three elements using a single loop, and you don't need to modify the array.
When you come across a new largest element, you need to shift the previous largest and the previous second-largest down by one position.
Similarly, when you find a new second-largest element, you need to shift maxel2 into maxel3.
Instead of using the three variables, you might want to employ an array. This will enable you to streamline the logic, and make it easy to generalize to k largest elements.
Make 3 passes over array: on first pass find value and 1st index of maximum element M1, on second pass find value and 1st index of maximum element M2 which is lesser than M1 and on third pass find value/1st index M3 < M2.
Try this code it will work :)
public class Array
{
public void getMax( double ar[] )
{
double max1 = ar[0]; // Assume the first
double max2 = ar[0]; // element in the array
double max3 = ar[0]; // is the maximum element.
int ZERO = 0;
// Variable to store inside it the index of the max value to set it to zero.
for( int i = 0; i < ar.length; i++ )
{
if( ar[i] >= max1)
{
max1 = ar[i];
ZERO = i;
}
}
ar[ZERO] = 0; // Set the index contains the 1st max to ZERO.
for( int j = 0; j < ar.length; j++ )
{
if( ar[j] >= max2 )
{
max2 = ar[j];
ZERO = j;
}
}
ar[ZERO] = 0; // Set the index contains the 2st max to ZERO.
for( int k = 0; k < ar.length; k++ )
{
if( ar[k] >= max3 )
{
max3 = ar[k];
ZERO = k;
}
}
System.out.println("1st max:" + max1 + ", 2nd: " +max2 + ",3rd: "+ max3);
}
public static void main(String[] args)
{
// Creating an object from the class Array to be able to use its methods.
Array array = new Array();
// Creating an array of type double.
double a[] = {2.2, 3.4, 5.5, 5.5, 6.6, 5.6};
array.getMax( a ); // Calling the method that'll find the 1st max, 2nd max, and and 3rd max.
}
}
I suggest making a single pass instead of three for optimization. The code below works for me. Note that the code does not assert that listx has at least 3 elements. It is up to you to decide what should happen in case it contains only 2 elements or less.
What I like about this code is that it only does one pass over the array, which in its best case would have faster running time compared to doing three passes, with a factor proportionate to the number of elements in listx.
Assume i1, i2 and i3 store the indices of the three greatest elements in listx, and i0 is one of i1, i2 and i3 that points to the smallest element. In the beginning, i1 = i2 = i3 because we haven't found the largest elements yet. So let i0 = i1. If we find a new index j such that that listx[j] > listx[i0], we set i0 = j, replacing that old index with an index that leads to a greater element. Then we find the index among i1, i2 and i3 that now leads to the smallest element of out the three, so that we can safely discard that one in case a new large element comes along.
Note: This code is in C, so translate it to Java if you want to use it. I made sure to use similar syntax to make that easier. (I wrote it in C because I lacked a Java testing environment.)
void maxar(float listx[], int count) {
int maxidx[3] = {0};
/* The index of the 3rd greatest element
* in listx.
*/
int max_3rd = 0;
for (int i = 0; i < count; i++) {
if (listx[maxidx[max_3rd]] < listx[i]) {
/* Exchange 3rd greatest element
* with new greater element.
*/
maxidx[max_3rd] = i;
/* Find index of smallest maximum. */
for (int j = (max_3rd + 1) % 3; j != max_3rd; j = (j + 1) % 3) {
if (listx[maxidx[j]] < listx[maxidx[max_3rd]]) {
max_3rd = j;
}
}
}
}
/* `maxidx' now contains the indices of
* the 3 greatest values in `listx'.
*/
printf("3 maximum elements (unordered):\n");
for (int i = 0; i < 3; i++) {
printf("index: %2d, element: %f\n", maxidx[i], listx[maxidx[i]]);
}
}
public class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int thirdLargest=0;
int largest = 0;
int arr[] = {5,4,3,8,12,95,14,376,37,2,73};
for (int i = 0; i < arr.length; i++) {
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
if(thirdLargest<arr[i] && secondlargest!=arr[i] && largest!=arr[i] && thirdLargest<largest && thirdLargest<secondlargest)
thirdLargest =arr[i];
}
System.out.println("Largest number is: " + largest);
System.out.println("Second Largest number is: " + secondlargest);
System.out.println("third Largest number is: " + thirdLargest);
}
}
def third_mar_array(arr):
max1=0
max2=0
max3=0
for i in range(0,len(arr)-1):
if max1<arr[i]:
max1=arr[i]
max_in1=i
arr[max_in1]=0
for j in range(0,len(arr)-1):
if max2<arr[j]:
max2=arr[j]
max_in2=j
arr[max_in2]=0
for k in range(0,len(arr)-1):
if max3<arr[k]:
max3=arr[k]
max_in3=k
#arr[max_in3]=0
return max3
n=[5,6,7,3,2,1]
f=first_array(n)
print f
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
while (testcase-- > 0) {
int sizeOfArray = sc.nextInt();
int[] arr = new int[sizeOfArray];
for (int i = 0; i < sizeOfArray; i++) {
arr[i] = sc.nextInt();
}
int max1, max2, max3;
max1 = 0;
max2 = 0;
max3 = 0;
for (int i = 0; i < sizeOfArray; i++) {
if (arr[i] > max1) {
max3 = max2;
max2 = max1;
max1 = arr[i];
}
else if (arr[i] > max2) {
max3 = max2;
max2 = arr[i];
}
else if (arr[i] > max3) {
max3 = arr[i];
}
}
System.out.println(max1 + " " + max2 + " " + max3);
}
}
}

Categories