zoukankan      html  css  js  c++  java
  • leetcode--Best Time to Buy and Sell Stock

    1.题目描述

    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.

    2.解法分析

    实际上就是给出了一个数组a,数组中元素值为整数,找出数组中任意a[i]-a[j]的最大值,其中需满足i>=j

    此题是经典题型,最简单的解法是先将a转化为b,其中:b[i]= a[i+1]-a[i],然后求b[i]的子数组中和最大的一个(子数组可以为空),于是有了下面的代码:

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(prices.size() <=1)return 0;
            vector<int>::iterator iter;
            for(iter=prices.begin();iter!=prices.end()-1;++iter)
            {
                *iter = *(iter+1) - *iter;
            }
            
            int max = 0;
            int subSum =0;
            
            for(iter=prices.begin();iter!=prices.end()-1;++iter)
            {
                subSum = subSum + *iter;
                if(subSum>max)max = subSum;
                if(subSum <0)subSum=0;
            }
            
            return max;
            
        }
    };
  • 相关阅读:
    Java程序设计作业02
    Java程序设计作业01
    DS博客作业05
    DS博客作业04
    DS博客作业03
    DS博客作业02
    DS博客作业01
    C博客作业06
    C博客作业05
    C语言——数组作业批改
  • 原文地址:https://www.cnblogs.com/obama/p/3249987.html
Copyright © 2011-2022 走看看