Fork me on GitHub

best-time-to-buy-and-sell-stock

/**
*
* @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);
    }

}

  

posted @ 2019-07-25 15:54  gentleKay  阅读(190)  评论(0编辑  收藏  举报