Answered step by step
Verified Expert Solution
Question
1 Approved Answer
In the following code, I am not getting the desired output. What do I need to change so that it will output correctly. My output
In the following code, I am not getting the desired output. What do I need to change so that it will output correctly. My output should be:
----> [1.2, 2.1, 5.3, 5.3, 8.1]
----> [3.1, 7.0, 9.5, 9.8]
----> [3.1]
----> [3.1, 3.1, 3.2]
----> []
**********************************************************************
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static ListfindLongestIncreasingSequence(List list) { if (list.isEmpty()){ return Collections.emptyList(); } int n = list.size(); ArrayList d = new ArrayList<>(); ArrayList p = new ArrayList<>(); for (int i = 0; i < n; ++i) { d.add(1); p.add(-1); } for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (list.get(j) < list.get(i) && d.get(i) < d.get(j) + 1) { d.set(i, d.get(j) + 1); p.set(i, j); } } } int ans = d.get(0), pos = 0; for (int i = 1; i < n; i++) { if (d.get(i) > ans) { ans = d.get(i); pos = i; } } ArrayList subsequent = new ArrayList<>(); while (pos != -1) { subsequent.add(list.get(pos)); pos = p.get(pos); } ArrayList x = new ArrayList<>(); for (int i = subsequent.size() - 1; i >= 0; --i) { x.add(subsequent.get(i)); } return x; } public static void main(String[] args) { List list1 = new ArrayList<>(); Collections.addAll(list1, 3.1, 7.0, 1.2, 2.1, 5.3, 5.3, 8.1, 5.2, 6.6, 3.0, 4.3, 7.1, 8.7, 9.8, 1.9); printResult(list1); List list2 = new ArrayList<>(); Collections.addAll(list2, 3.1, 7.0, 9.5, 9.8); printResult(list2); List list3 = new ArrayList<>(); Collections.addAll(list3, 3.1, 3.0, 2.7, 2.1, 1.3, 1.2); printResult(list3); List list4 = new ArrayList<>(); Collections.addAll(list4, 3.1, 3.1, 3.2, 2.7, 2.1, 3.3, 1.2); printResult(list4); List list5 = new ArrayList<>(); printResult(list5); } public static void printResult(List list) { List result = findLongestIncreasingSequence(list); if (result.isEmpty()) { System.out.println("----->[]"); } else { System.out.println("----->" + result); } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started