LeetCode 121 Best Time to Buy and Sell Stock题解

来源:互联网 发布:淘宝放心淘怎么设置 编辑:程序博客网 时间:2024/06/06 20:09

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

题目:

Say you have an array for which the ith element is the price of a given stock on day i.

给定一个数组,第i个数组元素的值表示第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.

如果你只被允许进行最多一次交易(即只允许买一次和卖一次股票),设计一个算法得到最大收益。

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.

算法思想:

从数组头部开始遍历,用一个int型的变量记录遍历过的数值中的最小值,一个int型变量来记录盈利值,遍历时如果遍历的值比最小值还小,那么更新最小值,否则,判断是否要更新盈利值。

Java代码实现:

public class Solution {    public int maxProfit(int prices[]) {        int minprice = Integer.MAX_VALUE;        int maxprofit = 0;        for (int i = 0; i < prices.length; i++) {            if (prices[i] < minprice)                minprice = prices[i];            else if (prices[i] - minprice > maxprofit)                maxprofit = prices[i] - minprice;        }        return maxprofit;    }}





0 0
原创粉丝点击