[LintCode] Best Time to Buy and Sell Stock II
public int maxProfit(int[] prices) { // write your code here int max = 0; for(int i = 1; i < prices.length; i++) { if(prices[i] – prices[i-1] > 0) max += prices[i] – prices[i-1]; } return max; }
public int maxProfit(int[] prices) { // write your code here int max = 0; for(int i = 1; i < prices.length; i++) { if(prices[i] – prices[i-1] > 0) max += prices[i] – prices[i-1]; } return max; }
public int majorityNumber(ArrayList<Integer> nums) { // write your code int index = -1; int count = 0; for(int i = 0 ; i < nums.size(); i++) { if(count == 0) { index = i; count ++; } else { if(nums.get(i) == nums.get(index)) count++; else count–; } } return nums.get(index); }
ArrayList<String> longestWords(String[] dictionary) { // write your code here ArrayList<String> res = new ArrayList<String>(); if(dictionary == null || dictionary.length == 0) return res; int len = dictionary[0].length(); for(int i = 0; i < dictionary.length; i++) { if(dictionary[i].length() == len) res.add(dictionary[i]); else if(dictionary[i].length() > len){ len = dictionary[i].length(); res.clear(); res.add(dictionary[i]); } } return res; }
public ArrayList<String> fizzBuzz(int n) { ArrayList<String> results = new ArrayList<String>(); for (int i = 1; i <= n; i++) { if (i % 15 == 0) { results.add(“fizz buzz”); } else if (i % 5 == 0) { results.add(“buzz”); } else if (i % 3 == 0) { results.add(“fizz”); } else { results.add(String.valueOf(i)); } } […]
public int fibonacci(int n) { // write your code here int first = 0; if(n == 1) return first; int second = 1; if(n == 2) return second; int third = 0; for(int i = 3; i <=n; i++) { third = first+ second; first = second; second = third; } return third; }
public String longestCommonPrefix(String[] strs) { // write your code here if(strs == null || strs.length == 0) return “”; String prefix = strs[0]; for(int i = 1; i < strs.length; i++) { int j = 0; while(j < prefix.length() && j < strs[i].length() && prefix.charAt(j)==strs[i].charAt(j)) j++; prefix = prefix.substring(0,j); } return prefix; }