best-time-to-buy-and-sell-stock 客官°小女子只卖身不卖艺 2021-11-09 08:34 165阅读 0赞 /\*\* \* \* @author gentleKay \* Say you have an array for which the i th element is the price of a given stock on day i. \* If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), \* design an algorithm to find the maximum profit. \* \* 假设您有一个数组,其中第i个元素是第一天给定股票的价格。 \* 如果你只被允许完成最多一笔交易(即买卖一份股票), \* 设计一个算法来找到最大利润。 \*/ #### 第一种方法: #### /** * * @author gentleKay * Say you have an array for which the i th element is the price of a given stock on day i. * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), * design an algorithm to find the maximum profit. * * 假设您有一个数组,其中第i个元素是第一天给定股票的价格。 * 如果你只被允许完成最多一笔交易(即买卖一份股票), * 设计一个算法来找到最大利润。 */ public class Main11 { public static void main(String[] args) { // TODO Auto-generated method stub int[] prices = {1}; System.out.println(Main11.maxProfit(prices)); } public static int maxProfit(int[] prices) { int min = Integer.MAX_VALUE; int res = 0; for (int i=0;i<prices.length;i++) { min = Math.min(min, prices[i]); res = Math.max(res, prices[i] - min); } return res; } } #### 第二种方法: #### import java.util.ArrayList; import java.util.Collections; /** * * @author gentleKay * Say you have an array for which the i th element is the price of a given stock on day i. * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), * design an algorithm to find the maximum profit. * * 假设您有一个数组,其中第i个元素是第一天给定股票的价格。 * 如果你只被允许完成最多一笔交易(即买卖一份股票), * 设计一个算法来找到最大利润。 */ public class Main11 { public static void main(String[] args) { // TODO Auto-generated method stub int[] prices = {1}; System.out.println(Main11.maxProfit(prices)); } public static int maxProfit(int[] prices) { if (prices.length < 1) { return 0; } ArrayList<Integer> array = new ArrayList<>(); for (int i=0;i<prices.length;i++) { for (int j=i+1;j<prices.length;j++) { if (prices[j] - prices[i] < 0) { continue; } array.add(prices[j] - prices[i]); } } Collections.sort(array); if (array.isEmpty()) { return 0; } return array.get(array.size()-1); } } 转载于:https://www.cnblogs.com/strive-19970713/p/11244796.html
还没有评论,来说两句吧...