zoukankan      html  css  js  c++  java
  • 121. 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.

    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: 5
    
    max. 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: 0
    
    In this case, no transaction is done, i.e. max profit = 0.
    

    给定一个序列的股票价格,允许一次交易,找到出最大的盈利。其中要求是需要先买(先持有)才能再卖。

    说白了就是给定一个整数数组,数组后面的元素减去前面的数组元素,差值最大的是多少。

    先举一个例子 [1,2,3,4,5,6],最大的差值为5, 计算的过程为后面的元素减去前面一个元素的和,即sum([0,1,1,1,1,1]),可以看出最大的差值是前面差值的累积。再看例子[7,1,5,3,6,4],后面元素和前面元素的差值为[0,-6,,4,-2,3,-2]tmp += prices[i] - prices[i-1],如果tmp小于0,则重置为0.

    
    class Solution {
        public int maxProfit(int[] prices) {
            int max = 0;
            int tmp = 0;
            for(int i = 0; i < prices.length - 1; i++)
    
            {
                tmp = Math.max(0,tmp += prices[i+1]-prices[i]);
    
                max = Math.max(tmp,max);
            }
            return max;
        }
    
    }
    
    
  • 相关阅读:
    最近总结
    公开MQTT服务器列表
    MQTT资料收集
    开源游戏
    B站学习资料
    MQTT资料
    都2020年了,还再问GET和POST的区别?【深度好文】
    以“用户登录”测试谈用例编写
    接口自动化测试框架9项必备功能
    一篇文章了解软件测试基础知识
  • 原文地址:https://www.cnblogs.com/wxshi/p/7613716.html
Copyright © 2011-2022 走看看