Best Time to Buy and Sell Stock

来源:互联网 发布:java mysql orm 编辑:程序博客网 时间:2024/05/14 17:05


题目描述:Say you have an array for which the ith element is the price of a given stock on dayi.

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.

解题思路:只能有一次交易,只需找到最大间隔差

Java代码实现:

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length==0) return 0;        int min=prices[0],max=prices[0];        int profit=max-min;        for(int i=1;i<prices.length;i++){            if(prices[i]>max) max=prices[i];            if(prices[i]<min) {                if(profit<(max-min)) profit=max-min;                min=prices[i];                max=prices[i];            }        }        if(profit<(max-min)) profit=max-min;        return profit;    }}

原题题目:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

0 0