【LeetCode】121.Best Time to Buy and Sell Stock解题报告

来源:互联网 发布:源码资本海外招聘 编辑:程序博客网 时间:2024/06/05 09:22

【LeetCode】121.Best Time to Buy and Sell Stock解题报告

tags: Array

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

  Say you have an array for which the ith 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.

Example1:

Input: [7, 1, 5, 3, 6, 4] Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example2:

Input: [7, 6, 4, 3, 1] Output: 0

In this case, no transaction is done, i.e. max profit = 0.

题意:从前到后,找两个递增的数,求最大差值。

Solution:

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length==0)  return 0;        int low=prices[0];        int ans=0;        for(int i=1;i<prices.length;i++){            if(prices[i]<low){                low=prices[i];            }else if(prices[i]-low>ans){                ans=prices[i]-low;            }        }        return ans;    }}

Date:2017年6月23日

阅读全文
0 0
原创粉丝点击