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

    [解题思路]

    记录一个最小值,每次拿当前值与最小值比较,如果两者差>profit,则更新profit

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int profit = 0, min = Integer.MAX_VALUE;
     6         for(int i = 0; i < prices.length; i++){
     7             if(prices[i] < min){
     8                 min = prices[i];
     9             }
    10             if(prices[i] - min > profit){
    11                 profit = prices[i] - min;
    12             }
    13         }
    14         return profit;
    15     }
    16 }
  • 相关阅读:
    占卜DIY
    飞行员兄弟
    给树染色
    国王游戏
    雷达设备
    畜栏预定
    防晒
    去雨系列论文笔记
    First day
    如何用fprintf写十六进制 并控制格式
  • 原文地址:https://www.cnblogs.com/feiling/p/3264470.html
Copyright © 2011-2022 走看看